-1

I am new to Android Programming. In my application I am inserting data to 2 SQLite database tables teams and teams_vs_leagues. Directly following an insert I want to go to a new activity to view and edit the data from the insert. I used similar code in another Class but I was passing the position of an item in a ListView onClickListener and when I try to pass the id on a Button onClickListener I am receiving the error below.

Process: com.example.android.soccerleaguesapp, PID: 14919
   java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.soccerleaguesapp/com.example.android.soccerleaguesapp.DisplayTeam}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2344)
       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2404)
       at android.app.ActivityThread.access$800(ActivityThread.java:145)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1323)
       at android.os.Handler.dispatchMessage(Handler.java:102)
       at android.os.Looper.loop(Looper.java:135)
       at android.app.ActivityThread.main(ActivityThread.java:5319)
       at java.lang.reflect.Method.invoke(Native Method)
       at java.lang.reflect.Method.invoke(Method.java:372)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1016)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)
    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
       at com.example.android.soccerleaguesapp.DisplayTeam.onCreate(DisplayTeam.java:36)
       at android.app.Activity.performCreate(Activity.java:5976)
       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2297)
       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2404) 
       at android.app.ActivityThread.access$800(ActivityThread.java:145) 
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1323) 
       at android.os.Handler.dispatchMessage(Handler.java:102) 
       at android.os.Looper.loop(Looper.java:135) 
       at android.app.ActivityThread.main(ActivityThread.java:5319) 
       at java.lang.reflect.Method.invoke(Native Method) 
       at java.lang.reflect.Method.invoke(Method.java:372) 
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1016) 
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811) 

addTeam method

public void addTeam() {
 //set onclick method on add_team button
 add_team.setOnClickListener(
  new View.OnClickListener() {
   @Override
   public void onClick(View v) {
    //Call Team class and declare insert values for createTeam method
    Team team = new Team();
    team.setTeamName(team_name.getText().toString());
    team.setPath(picturePath);
    team.setLeague_id(leagueIdParse);
    //set long as the id of insert, used to pass into intent
    long id = myDb.createTeam(team);

    //Toast message to show that team has been successfully added
    Toast.makeText(add_team.this, team_name.getText().toString() + " successfully added", Toast.LENGTH_SHORT).show();

    Intent intent =
     new Intent(add_team.this, DisplayTeam.class);
    intent.putExtra("TEAM", (new Gson()).toJson(id));
    startActivity(intent);

   }
  }
 );
}

createTeam method

public long createTeam(Team team) {
  //Create SQLiteDatabase instance
  SQLiteDatabase db = this.getWritableDatabase();

  //setup values variable to be passed in insert to teams table
  ContentValues values = new ContentValues();

  //values of each column to be inserted into table from argument strings
  values.put(TEAM_NAME, team.getTeamName());
  values.put(IMAGE, team.getPath());

  //insert values into teams table
  long result = db.insert(TEAMS_TABLE, null, values);

  //new ContentValues instance for values to passed in insert into teams_vs_leagues table
  ContentValues newValues = new ContentValues();

  //values of each column to be inserted into table from argument strings
  newValues.put(TEAM_ID, result);
  newValues.put(LEAGUE_ID, team.getLeagueId());
  newValues.put(POINTS, 0);

  //insert values into teams_vs_leagues table
  long newResult = db.insert(TEAMS_VS_LEAGUES_TABLE, null, newValues);

  return result;

DisplayTeam class

public class DisplayTeam extends AppCompatActivity {
 private Team team;
 private ImageView imageView;
 private TextView teamName;
 private String jstring;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.display_team);
  imageView = (ImageView) findViewById(R.id.display_image_view);
  teamName = (TextView) findViewById(R.id.text_view_description);
  Bundle extras = getIntent().getExtras();

  if (extras != null) {
   jstring = extras.getString("TEAM");
  }
  team = getTeam(jstring);
  teamName.setText(team.toString());
  Display display = getWindowManager().getDefaultDisplay();
  Point size = new Point();
  display.getSize(size);
  int width = size.x;
  int height = size.y;
  imageView.setImageBitmap(ImageResizer
   .decodeSampledBitmapFromFile(team.getPath(), width, height));
 }

 private Team getTeam(String team) {
  try {
   JSONObject job = new JSONObject(team);
   return (new Team(
    job.getInt("id"),
    job.getString("team_name"),
    job.getString("path"),
    job.getInt("league_id"),
    job.getString("league_name")));
  } catch (JSONException e) {
   e.printStackTrace();
  }
  return null;
 }

 /**
  * go back to add_gallery activity
  *
  * @param v
  */
 public void btnBackOnClick(View v) {
  startActivity(new Intent(this, add_team.class));
  finish();
 }

 /**
  * delete the current item;
  *
  * @param v
  */
 public void btnDeleteOnClick(View v) {
  DatabaseHelper db = new DatabaseHelper(this);
  db.deleteTeam(team);
  db.close();
  startActivity(new Intent(this, add_team.class));
  finish();
 }

 @Override protected void onSaveInstanceState(Bundle outState) {
  // Save the user's current game state
  if (jstring != null) {
   outState.putString("jstring", jstring);
  }
  // Always call the superclass so it can save the view hierarchy state
  super.onSaveInstanceState(outState);
 }

 @Override protected void onRestoreInstanceState(Bundle savedInstanceState) {
  // Always call the superclass so it can restore the view hierarchy
  super.onRestoreInstanceState(savedInstanceState);

  // Restore state members from saved instance
  if (savedInstanceState.containsKey("jstring")) {
   jstring = savedInstanceState.getString("jstring");
  }
 }
}

Team class

public class Team {
 private String team_name, path, league_name;
 int id, league_id;

 public Team(String team_name, String path,
  int league_id) {
  this.team_name = team_name;
  this.path = path;
  this.league_id = league_id;
 }

 public Team(String team_name, String path,
  int league_id, String league_name) {
  this.team_name = team_name;
  this.path = path;
  this.league_id = league_id;
  this.league_name = league_name;
 }

 public Team(int keyId, String team_name, String path,
  int league_id) {
  this.id = keyId;
  this.team_name = team_name;
  this.path = path;
  this.league_id = league_id;
 }

 public Team(int keyId, String team_name, String path,
  int league_id, String league_name) {
  this.id = keyId;
  this.team_name = team_name;
  this.path = path;
  this.league_id = league_id;
  this.league_name = league_name;
 }

 //empty constructor
 public Team() {}

 public Team(int keyId) {
  this.id = keyId;

 }

 /**
  * Gets id.
  *
  * @return Value of id.
  */
 public int getId() {
  return id;
 }

 // setting id
 public void setId(int keyId) {
  this.id = keyId;
 }

 /**
  * Gets league_id.
  *
  * @return Value of league_id.
  */
 public int getLeagueId() {
  return league_id;
 }

 /**
  * Gets team_name.
  *
  * @return Value of team_name.
  */
 public String getTeamName() {
  return team_name;
 }

 /**
  * Gets league_name.
  *
  * @return Value of league_name.
  */
 public String getLeagueName() {
  return league_name;
 }

 /**
  * Sets new team_name.
  *
  * @param team_name New value of team_name.
  */
 public void setTeamName(String team_name) {
  this.team_name = team_name;
 }

 /**
  * Sets new league_id.
  *
  * @param league_id New value of league_id.
  */
 public void setLeague_id(int league_id) {
  this.league_id = league_id;
 }

 /**
  * Sets new path.
  *
  * @param path New value of path.
  */
 public void setPath(String path) {
  this.path = path;
 }

 /**
  * Gets path.
  *
  * @return Value of path.
  */
 public String getPath() {
  return path;
 }
}

If you require any more information, do not hesitate to contact me. Any help would be greatly appreciated.

mcclosa
  • 943
  • 7
  • 29
  • 59
  • replace this with intent.putExtra("TEAM", (new Gson()).toJson(id)); with intent.putExtra("TEAM", (new Gson()).toJson(team)); – dex Apr 11 '16 at 03:52
  • Still receiving same error, I am afraid – mcclosa Apr 11 '16 at 03:55
  • @mcclossa It would be good if you share the Team class also. – dex Apr 11 '16 at 04:02
  • why are you not using gson while retrieving the data ? – dex Apr 11 '16 at 04:05
  • @dex I added the `Team` class to my question. I'm very much a beginner and was following a tutorial and this was how they passed and received the data, along it was from a `ListView` – mcclosa Apr 11 '16 at 04:14

1 Answers1

1

On addTeam Method, You are only passing Id..

Intent intent = new Intent(add_team.this, DisplayTeam.class);
intent.putExtra("TEAM", (new Gson()).toJson(id));

And in getTeam() method, you are trying to get whole object from json string which contain only id, so it's throwing JSONException while you trying to get any other object then id. and hence you are getting null value in team = getTeam(jstring); and it's followed by NullPointerException in next line.

private Team getTeam(String team) {
  try {
   JSONObject job = new JSONObject(team);
   return (new Team(
    job.getInt("id"),
    job.getString("team_name"),
    job.getString("path"),
    job.getInt("league_id"),
    job.getString("league_name")));
  } catch (JSONException e) {
   e.printStackTrace();
  }
  return null;
}
Dhaval Patel
  • 10,119
  • 5
  • 43
  • 46
  • Thank you for the answer, how would I go about passing even just the `id`, `team_name` and `path`? Or is there perhaps a link for a tutorial on how to do this more effectively after an insert, as I am new to android a lot of the technical terms are a little over my head so I am unsure of what exactly to search for in these scenarios? – mcclosa Apr 11 '16 at 04:17
  • As you are already using `SQLite`, Instead of passing json from one activity to another, I suggest you to pass only `id`, and in next activity get `Team` object from `SQLite` database based on received `Id`. – Dhaval Patel Apr 11 '16 at 04:22
  • Take a look at http://pastebin.com/iXcrvLzT sample code. – Dhaval Patel Apr 11 '16 at 04:28
  • I will give that a go, thank you. Might be a silly question but what does the `01` do in `long id = getIntent().getLongExtra("TEAM", 01);`? – mcclosa Apr 11 '16 at 04:30
  • As per doc, it's value to be returned if no value of the desired type is stored with the given name. So if you don't pass id parameter in intent and try to get id parameter from next activity, it will return default value(here it's 0l). – Dhaval Patel Apr 11 '16 at 04:33
  • @mcclosa is your problem resolved? – Dhaval Patel Apr 11 '16 at 07:22