Runtime error with passing data between activities. Android - java

I really can't figure out what's the problem here, I did almost the same example i got from somewhere on net and it's working, but this one reports a runtime error when I click on the button to switch to secondActivity. But before I set up onActivityResult in first and sending result in second activity, it switched fine.
It's a little bit longer code, but it's nothing complicated. In first activity you click button to go to second activity, and there you pick two numbers, which are stored in object and sent by intent back to the first activity, and in first activity in textview you get the total of those numbers.
MainActivity
package com.example.parcelablevezba4;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView tv1;
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView)findViewById(R.id.tv1);
btn = (Button)findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(MainActivity.this, SecondActivity.class);
startActivityForResult(i, 42);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 42){
if(resultCode == RESULT_OK){
Object obj2 = data.getParcelableExtra("obje");
int total = obj2.getFirstSummand() + obj2.getSecondSummand();
tv1.setText(obj2.getFirstSummand()+"+"+obj2.getSecondSummand()+"is "+total);
}else if(resultCode == RESULT_CANCELED){
Toast.makeText(getApplicationContext(), "CANCELED", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
SecondActivity
package com.example.parcelablevezba4;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.content.Intent;
public class SecondActivity extends Activity {
EditText et1;
EditText et2;
Button btnOk;
int firstSummand;
int secondSummand;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
et1 = (EditText)findViewById(R.id.etFirst);
et2 = (EditText)findViewById(R.id.etSecond);
btnOk = (Button)findViewById(R.id.btnOk);
firstSummand = Integer.parseInt(et1.getText().toString());
secondSummand = Integer.parseInt(et2.getText().toString());
btnOk.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent resultIntent = new Intent();
Object obj = new Object();
obj.setFirstSummand(firstSummand);
obj.setSecondSummand(secondSummand);
resultIntent.putExtra("obje", obj);
setResult(RESULT_OK,resultIntent);
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
}
Object class
package com.example.parcelablevezba4;
import android.os.Parcel;
import android.os.Parcelable;
public class Object implements Parcelable {
private int firstSummand;
private int secondSummand;
public Object(){}
public Object(Parcel p){
this.firstSummand; = p.readInt();
this.secondSummand; = p.readInt();
}
public int getFirstSummand(){
return this.firstSummand;
}
public int getSecondSummand(){
return this.secondSummand;;
}
public void setFirstSummand(int f){
this.firstSummand = f;
}
public void setSecondSummand(int s){
this.secondSummand; = s;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel p, int flag) {
p.writeInt(firstSummand);
p.writeInt(secondSummand);
}
public static Parcelable.Creator<Object> CREATOR = new Parcelable.Creator<Object>() {
#Override
public Object createFromParcel(Parcel source) {
// TODO Auto-generated method stub
return new Object(source);
}
#Override
public Object[] newArray(int size) {
// TODO Auto-generated method stub
return new Object[size];
}
};
}
I translated this from my language, so if I mistyped somewhere sorry about that.
Error
08-17 13:20:22.933: E/AndroidRuntime(743): FATAL EXCEPTION: main
08-17 13:20:22.933: E/AndroidRuntime(743): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.parcelablevezba4/com.example.parcelablevezba4.SecondActivity}: java.lang.NumberFormatException: unable to parse '' as integer
08-17 13:20:22.933: E/AndroidRuntime(743): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
08-17 13:20:22.933: E/AndroidRuntime(743): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
08-17 13:20:22.933: E/AndroidRuntime(743): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
08-17 13:20:22.933: E/AndroidRuntime(743): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
08-17 13:20:22.933: E/AndroidRuntime(743): at android.os.Handler.dispatchMessage(Handler.java:99)
08-17 13:20:22.933: E/AndroidRuntime(743): at android.os.Looper.loop(Looper.java:123)
08-17 13:20:22.933: E/AndroidRuntime(743): at android.app.ActivityThread.main(ActivityThread.java:3683)
08-17 13:20:22.933: E/AndroidRuntime(743): at java.lang.reflect.Method.invokeNative(Native Method)
08-17 13:20:22.933: E/AndroidRuntime(743): at java.lang.reflect.Method.invoke(Method.java:507)
08-17 13:20:22.933: E/AndroidRuntime(743): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-17 13:20:22.933: E/AndroidRuntime(743): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-17 13:20:22.933: E/AndroidRuntime(743): at dalvik.system.NativeStart.main(Native Method)
08-17 13:20:22.933: E/AndroidRuntime(743): Caused by: java.lang.NumberFormatException: unable to parse '' as integer
08-17 13:20:22.933: E/AndroidRuntime(743): at java.lang.Integer.parseInt(Integer.java:362)
08-17 13:20:22.933: E/AndroidRuntime(743): at java.lang.Integer.parseInt(Integer.java:332)
08-17 13:20:22.933: E/AndroidRuntime(743): at com.example.parcelablevezba4.SecondActivity.onCreate(SecondActivity.java:30)
08-17 13:20:22.933: E/AndroidRuntime(743): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-17 13:20:22.933: E/AndroidRuntime(743): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
08-17 13:20:22.933: E/AndroidRuntime(743): ... 11 more

It looks like one of your EditTexts are returning an empty string:
firstSummand = Integer.parseInt(et1.getText().toString());
secondSummand = Integer.parseInt(et2.getText().toString());
And then you try to parse that empty string.
Add a log before or even better a check:
String edit1 = et1.getText().toString();
String edit2 = et2.getText().toString();
Log.e("TAG", "First: "+edit1+" Second: "+edit2);
firstSummand = (edit1.isEmpty()) ? 0 : Integer.parseInt(edit1);
secondSummand = (edit2.isEmpty()) ? 0 : Integer.parseInt(edit2);

Related

how to implement an adapter for a listview in my specific case?

I have a list of Claim objects, each claim object is initialized with a name and an expense list.
i made an adapter for the listview for the claims. what I am trying to do now is create an adaptor for the expenses. Since each claim has its own expense list, i cannot just make a general adapter. i need to make an adapter for a specific Claim, or am thinking of this wrong? here is what I did..
JUST TO BE CLEAR< MY QUESTION IS: How do I make an adaptor for the list initializd with the expenses, and open that list-view to see the expenses of a specific claim when I click on it?
package app.zioueche_travelexpense;
import java.util.ArrayList;
import java.util.Collection;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.Toast;
//figure out how to add claim in different page. so we can add date range.
public class AddClaim extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_claim);
//adapter for claim view this one works. it is the expenses one that i do not know how to implement
ListView listView = (ListView) findViewById(R.id.claimListView);
Collection<Claim> claims = ClaimListController.getClaimList().getClaim();
final ArrayList<Claim> list = new ArrayList<Claim>(claims);
final ArrayAdapter<Claim> claimAdapter = new ArrayAdapter<Claim>(this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(claimAdapter);
//Added observer pattern
ClaimListController.getClaimList().addListener(new Listener(){
#Override
public void update(){
list.clear();
Collection<Claim> claims = ClaimListController.getClaimList().getClaim();
list.addAll(claims);
claimAdapter.notifyDataSetChanged();
}
});
//SINGLE TAP FUNCTION
listView.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//adapter expenses I DO NOT KNOW HOW TO IMPLEMENT THIS
ListView expView = (ListView) findViewById(R.id.ExpenseListView);
Collection<Expense> expenses = list.get(position).getExpenses();
final ArrayList<Expense> expense = new ArrayList<Expense>(expenses);
final ArrayAdapter<Expense> expAdap = new ArrayAdapter<Expense>(AddClaim.this, android.R.layout.simple_list_item_1, expense);
expView.setAdapter(expAdap); //THIS IS MY LINE 64
}
});
//LONG CLICK FUNCTIONS
listView.setOnItemLongClickListener(new OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
final int finalPosition = position;
PopupMenu popup = new PopupMenu(AddClaim.this, view);
popup.getMenuInflater().inflate(R.menu.add_claim, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
//DELETE button check.
if (item.getTitle().equals("Delete")){
AlertDialog.Builder adb = new AlertDialog.Builder(AddClaim.this);
adb.setMessage("Delete "+ list.get(finalPosition).toString()+"?");
adb.setCancelable(true);
adb.setPositiveButton("Delete",new OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
Claim claim = list.get(finalPosition);
ClaimListController.getClaimList().deleteClaim(claim);
}
});
adb.setNegativeButton("Cancel",new OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
adb.show();
}//end of delete button check
//START of ADD EXPENSE check
if (item.getTitle().equals("Add Expense")){
Intent intent = new Intent(AddClaim.this, ExpenseAdd.class);
intent.putExtra("somename", finalPosition);
startActivity(intent);
}
//end of add expense check
return true;
}
});
popup.show();
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.add_claim, menu);
return true;
}
protected void onDeleteClick(final int position, final ArrayList<Claim> list){
AlertDialog.Builder adb = new AlertDialog.Builder(AddClaim.this);
adb.setMessage("Delete "+ list.get(position).toString()+"?");
adb.setCancelable(true);
adb.setPositiveButton("Delete",new OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
Claim claim = list.get(position);
ClaimListController.getClaimList().deleteClaim(claim);
}
});
adb.setNegativeButton("Cancel",new OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
adb.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void addClaimView(MenuItem item){
Toast.makeText(this, "going to claim creation page", Toast.LENGTH_SHORT).show();
setContentView(R.layout.claim_add_page);
}
public void addClaims(View v){
ClaimListController ct = new ClaimListController();
EditText textView = (EditText) findViewById(R.id.add_claim_field);
String added = textView.getText().toString();
if (!TextUtils.isEmpty(added)){
final String t = format("added",added);
ct.addClaim(new Claim(added));
Toast.makeText(this, t, Toast.LENGTH_SHORT).show();
textView.setText("");
setContentView(R.layout.claim_list);
//Intent intent = new Intent(MainActivity.this, AddClaim.class);
//startActivity(intent);
}else{
Toast.makeText(AddClaim.this,"Please type something before adding", Toast.LENGTH_SHORT).show();
}
}
private String format(String string, String added) {
String formats = string +" "+ added;
return formats;
}
}
As you can see, i made my listview adapter for the expenses inside the onclick method, since i need the position to get the expense list out of the specific claim.
How can I do this/ when I run this code I get null pointer exceptions on line 64.
here is the log cat.
01-24 02:01:15.434: E/AndroidRuntime(1099): FATAL EXCEPTION: main
01-24 02:01:15.434: E/AndroidRuntime(1099): java.lang.NullPointerException
01-24 02:01:15.434: E/AndroidRuntime(1099): at app.zioueche_travelexpense.AddClaim$2.onItemClick(AddClaim.java:64)
01-24 02:01:15.434: E/AndroidRuntime(1099): at android.widget.AdapterView.performItemClick(AdapterView.java:298)
01-24 02:01:15.434: E/AndroidRuntime(1099): at android.widget.AbsListView.performItemClick(AbsListView.java:1100)
01-24 02:01:15.434: E/AndroidRuntime(1099): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2749)
01-24 02:01:15.434: E/AndroidRuntime(1099): at android.widget.AbsListView$1.run(AbsListView.java:3423)
01-24 02:01:15.434: E/AndroidRuntime(1099): at android.os.Handler.handleCallback(Handler.java:725)
01-24 02:01:15.434: E/AndroidRuntime(1099): at android.os.Handler.dispatchMessage(Handler.java:92)
01-24 02:01:15.434: E/AndroidRuntime(1099): at android.os.Looper.loop(Looper.java:137)
01-24 02:01:15.434: E/AndroidRuntime(1099): at android.app.ActivityThread.main(ActivityThread.java:5041)
01-24 02:01:15.434: E/AndroidRuntime(1099): at java.lang.reflect.Method.invokeNative(Native Method)
01-24 02:01:15.434: E/AndroidRuntime(1099): at java.lang.reflect.Method.invoke(Method.java:511)
01-24 02:01:15.434: E/AndroidRuntime(1099): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-24 02:01:15.434: E/AndroidRuntime(1099): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-24 02:01:15.434: E/AndroidRuntime(1099): at dalvik.system.NativeStart.main(Native Method)
01-24 02:01:17.814: E/Trace(1117): error opening trace file: No such file or directory (2)

Facebook API. Java Code for Android Project Incorrect.

Having serious problems with a lab and I am not the only one. I have my emulator running fine with all Facebook example apps. FacebookSDK and HelloFacebookSample project all work fine. It is something in the code that is incorrect. All xml, and manifest coding is correct. I am sure it is something in the Java code. It compiles, it prompts a Log-In then it asks about permissions, then it crashes.
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Session.StatusCallback;
import com.facebook.model.GraphObject;
import com.facebook.SessionState;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode,
resultCode, data);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
final TextView newsFeedTextView = (TextView) rootView
.findViewById(R.id.newsFeed);
StatusCallback mCallback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
/* make the API call */
new Request(session, "/GmitClubsandsocieties/feed", null,
HttpMethod.GET, new Request.Callback() {
#Override
public void onCompleted(Response response) {
/* check logcat for responce */
System.out.println(response);
newsFeedTextView
.setText(parseDataFromFQLResponse(response));
}
}).executeAsync();
}
}
};
Session.OpenRequest request = new Session.OpenRequest(getActivity());
// request.setPermissions(Arrays.asList("read_stream"));
request.setCallback(mCallback);
// get active session
Session mFacebookSession = Session.getActiveSession();
if (mFacebookSession == null || mFacebookSession.isClosed()) {
mFacebookSession = new Session(getActivity());
}
// mFacebookSession.openForRead(request);
mFacebookSession.openForRead(request);
return rootView;
}
}
private static String parseDataFromFQLResponse(Response response) {
StringBuilder responseText = new StringBuilder(" ");
try {
GraphObject go = response.getGraphObject();
JSONObject jso = go.getInnerJSONObject();
JSONArray arr = jso.getJSONArray( "data" );
for (int i = 0; i < (arr.length()); i++) {
JSONObject json_obj = arr.getJSONObject(i);
responseText.append(String.format("Message: %s\n\n",
json_obj.getString("message")));
}
} catch (Throwable t) {
t.printStackTrace();
}
return responseText.toString();
}
}
This is the logFile:
04-24 09:57:28.453: D/AndroidRuntime(2574): Shutting down VM
04-24 09:57:28.453: W/dalvikvm(2574): threadid=1: thread exiting with uncaught exception (group=0xb2ae0ba8)
04-24 09:57:28.513: E/AndroidRuntime(2574): FATAL EXCEPTION: main
04-24 09:57:28.513: E/AndroidRuntime(2574): Process: ie.gmit.facebooknewsfeed, PID: 2574
04-24 09:57:28.513: E/AndroidRuntime(2574): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=64206, result=-1, data=Intent { (has extras) }} to activity {ie.gmit.facebooknewsfeed/ie.gmit.facebooknewsfeed.MainActivity}: java.lang.NullPointerException
04-24 09:57:28.513: E/AndroidRuntime(2574): at android.app.ActivityThread.deliverResults(ActivityThread.java:3365)
04-24 09:57:28.513: E/AndroidRuntime(2574): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3408)
04-24 09:57:28.513: E/AndroidRuntime(2574): at android.app.ActivityThread.access$1300(ActivityThread.java:135)
04-24 09:57:28.513: E/AndroidRuntime(2574): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1244)
04-24 09:57:28.513: E/AndroidRuntime(2574): at android.os.Handler.dispatchMessage(Handler.java:102)
04-24 09:57:28.513: E/AndroidRuntime(2574): at android.os.Looper.loop(Looper.java:136)
04-24 09:57:28.513: E/AndroidRuntime(2574): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-24 09:57:28.513: E/AndroidRuntime(2574): at java.lang.reflect.Method.invokeNative(Native Method)
04-24 09:57:28.513: E/AndroidRuntime(2574): at java.lang.reflect.Method.invoke(Method.java:515)
04-24 09:57:28.513: E/AndroidRuntime(2574): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-24 09:57:28.513: E/AndroidRuntime(2574): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-24 09:57:28.513: E/AndroidRuntime(2574): at dalvik.system.NativeStart.main(Native Method)
04-24 09:57:28.513: E/AndroidRuntime(2574): Caused by: java.lang.NullPointerException
04-24 09:57:28.513: E/AndroidRuntime(2574): at ie.gmit.facebooknewsfeed.MainActivity.onActivityResult(MainActivity.java:40)
04-24 09:57:28.513: E/AndroidRuntime(2574): at android.app.Activity.dispatchActivityResult(Activity.java:5423)
04-24 09:57:28.513: E/AndroidRuntime(2574): at android.app.ActivityThread.deliverResults(ActivityThread.java:3361)
04-24 09:57:28.513: E/AndroidRuntime(2574): ... 11 more
04-24 09:57:32.283: I/Process(2574): Sending signal. PID: 2574 SIG: 9
Your data parameter may not be properly populated. In onActivityResult
add the line Bundle bundle = data.getExtras();

android app crashes when killing one activity and start another one

There is one button I set in Scene2.java.I want to use the button to get in other activities Scene3.java,GameOver.java Everything worked fine until its about to open the new activity,every time the app crashed there. I want to know if there're any mistake I made in the connection,which I mean the newIntent and getIntent inScene2.java GameOver.javaand Scene3.java
Scene2.java
package com.group5.littlered;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class Scene2 extends Activity {
MediaPlayer bird;
MediaPlayer bgm;
int position = 0;
String[] conversation;
TextView frame;
ImageView conframe;
final String[] ListStr = { "Wake up and ask her", "Peek her secretly" };
int plot = 0;
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_scene2);
Intent intent1 = getIntent();
conversation = getResources().getStringArray(R.array.scene2);
frame = (TextView) findViewById(R.id.textView1);
Button next = (Button) findViewById(R.id.wtf);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (position < 2) {
String sentence = conversation[position];
frame.setText(sentence + "");
position++;
} else {
if (plot < 1) {
AlertDialog choice = new AlertDialog.Builder(
Scene2.this).create();
choice.setTitle("Pick a choice");
choice.setMessage(" ");
choice.setButton("Get up and ask her what happened",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
plot = 1;
}
});
choice.setButton2("Peek her secretly",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
plot = 2;
position = 4;
}
});
choice.show();
} else {
if (plot < 2) {
if (position < 4) {
String sentence = conversation[position];
frame.setText(sentence + "");
position++;
} else {
Intent intent2 = new Intent(Scene2.this,
GameOver.class);
startActivity(intent2);
finish();
}
} else {
if (position < 6) {
String sentence = conversation[position];
frame.setText(sentence + "");
position++;
} else {
Intent intent3 = new Intent(Scene2.this,
Scene3.class);
startActivity(intent3);
finish();
}
}
}
}
}
});
// BGM
bgm = MediaPlayer.create(Scene2.this, R.raw.voyager);
bgm.setLooping(true);
bgm.start();
// bird
bird = MediaPlayer.create(Scene2.this, R.raw.bird);
bird.setLooping(false);
bird.start();
}
}
Scene3.java
package com.group5.littlered;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class Scene3 extends Activity {
int position = 0;
String[] conversation;
TextView frame;
ImageView conframe;
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_scene3);
Intent intent3 = getIntent();
conversation = getResources().getStringArray(R.array.scene1);
frame = (TextView) findViewById(R.id.textView1);
Button next = (Button) findViewById(R.id.wtf);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (position < 6) {
String sentence = conversation[position];
frame.setText(sentence + "");
position++;
} else {
{
}
}
}
});
}
}
Again sorry for my poor ENGLISH, plz tell me what I need to post more to help you understand my problem.
my logcat
04-30 09:37:39.497: E/AndroidRuntime(4862): FATAL EXCEPTION: main
04-30 09:37:39.497: E/AndroidRuntime(4862): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.group5.littlered/com.group5.littlered.Scene3}: java.lang.NullPointerException
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.os.Handler.dispatchMessage(Handler.java:99)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.os.Looper.loop(Looper.java:137)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.main(ActivityThread.java:5103)
04-30 09:37:39.497: E/AndroidRuntime(4862): at java.lang.reflect.Method.invokeNative(Native Method)
04-30 09:37:39.497: E/AndroidRuntime(4862): at java.lang.reflect.Method.invoke(Method.java:525)
04-30 09:37:39.497: E/AndroidRuntime(4862): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
04-30 09:37:39.497: E/AndroidRuntime(4862): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-30 09:37:39.497: E/AndroidRuntime(4862): at dalvik.system.NativeStart.main(Native Method)
04-30 09:37:39.497: E/AndroidRuntime(4862): Caused by: java.lang.NullPointerException
04-30 09:37:39.497: E/AndroidRuntime(4862): at com.group5.littlered.Scene3.onCreate(Scene3.java:45)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.Activity.performCreate(Activity.java:5133)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
04-30 09:37:39.497: E/AndroidRuntime(4862): ... 11 more
The line that is crashing is the line 45 of Scene3:
Button next = (Button) findViewById(R.id.wtf);
next.setOnClickListener(new View.OnClickListener() { // <-- THIS ONE
...
});
The cause is a NullPointerException. This means that the identifier "wtf" exists in R (this wouldn't compile otherwise) but is not found in the layer activity_scene3, as we wave the following statement line 38 of Scene3.onCreate():
setContentView(R.layout.activity_scene3); // and later on findViewById() returns `null`
You have to revisit this layout to ensure that the Button you are willing to access to actually exists, with the ID wtf.
Generally speaking, this is the danger in using a same ID in different layouts. This is prone to hide errors that would easily be found otherwise as this would just not compile.
Check your manifest file and add Scene3.java in it
<activity
android:name=".Scene3" >
</activity>
Always post question with exception, second this is may be you have not mention your other activity in manifest file like:
<activity
android:name=".Scene3">
</activity>
<activity
android:name=".GameOver">
</activity>

fatal error. launching activity in android

I want to access Confirmation activity from login activity. i was able to launch confirmation activity when i didn't have login and registration activity. login and registration works perfect without confirmation activity. and dashboard activity and confirmation activity works perfect without login and registration activity.
Registration Activity.
package com.example.androidhive;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.androidhive.library.DatabaseHandler;
import com.example.androidhive.library.UserFunctions;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class RegisterActivity extends Activity {
Button btnRegister;
Button btnLinkToLogin;
EditText inputFullName;
EditText inputEmail;
EditText inputPassword;
TextView registerErrorMsg;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
// Importing all assets like buttons, text fields
inputFullName = (EditText) findViewById(R.id.registerName);
inputEmail = (EditText) findViewById(R.id.registerEmail);
inputPassword = (EditText) findViewById(R.id.registerPassword);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
registerErrorMsg = (TextView) findViewById(R.id.register_error);
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(name, email, password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
}else{
// Error in registration
registerErrorMsg.setText("Error occured in registration");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
// Link to Login Screen
btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(i);
// Close Registration View
finish();
}
});
}
}
Login Activity:-
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.androidhive.library.DatabaseHandler;
import com.example.androidhive.library.UserFunctions;
public class LoginActivity extends Activity {
Button btnLogin;
Button btnLinkToRegister;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
// Importing all assets like buttons, text fields
inputEmail = (EditText) findViewById(R.id.loginEmail);
inputPassword = (EditText) findViewById(R.id.loginPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
loginErrorMsg = (TextView) findViewById(R.id.login_error);
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
Log.d("Button", "Login");
JSONObject json = userFunction.loginUser(email, password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully logged in
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Login Screen
finish();
}else{
// Error in login
loginErrorMsg.setText("Incorrect username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
}
Dashboard Activity:-
package com.example.androidhive;
import android.app.Activity;
import com.example.androidhive.ConfirmationActivity;
import com.example.androidhive.R;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Toast;
import android.widget.Button;
import com.example.androidhive.library.UserFunctions;
public class DashboardActivity extends Activity {
UserFunctions userFunctions;
Button btnLogout;
private String resultString="";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* Dashboard Screen for the application
* */
// Check login status in database
userFunctions = new UserFunctions();
if(userFunctions.isUserLoggedIn(getApplicationContext())){
setContentView(R.layout.dashboard);
btnLogout = (Button) findViewById(R.id.btnLogout);
btnLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
userFunctions.logoutUser(getApplicationContext());
Intent login = new Intent(getApplicationContext(), LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
});
}else{
// user is not logged in show login screen
Intent login = new Intent(getApplicationContext(), LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
}
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
#JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==0)
if (resultCode == RESULT_OK) {
//Use Data to get string
resultString = data.getStringExtra("RESULT_STRING");
LaunchWebView(resultString);
}
super.onActivityResult(requestCode, resultCode, data);
}
private void LaunchWebView(String resultString)
{
WebView engine=(WebView)findViewById(com.example.androidhive.R.id.web_engine);
//engine.getSettings().setJavaScriptEnabled(true);
String[] array=resultString.split(":");
engine.getSettings().setLoadsImagesAutomatically(true);
//engine.getSettings().setBuiltInZoomControls(true);
engine.getSettings().setUseWideViewPort(true);
engine.setWebChromeClient(new MyJavaScriptChromeClient());
engine.loadUrl("http://74.101.168.139/snapshot.cgi?user="+array[0]+"&pwd="+array[1]+"&count=0" + "&resolution=32"+ "&rate=6");
}
public void btnRefresh_ClicHandler(View view)
{
if(resultString!="")
LaunchWebView(resultString);
}
public void btnHome(View arg)
{
Intent intent=new Intent(this,ConfirmationActivity.class);
int result=0;
startActivityForResult(intent, result);
}
private class MyJavaScriptChromeClient extends WebChromeClient {
#Override
public boolean onJsAlert(WebView view, String url, String message,
JsResult result) {
// TODO Auto-generated method stub
return super.onJsAlert(view, null, message, result);
}
}
}
Confirmation Activity : -
package com.example.androidhive;
import com.example.androidhive.R;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class ConfirmationActivity extends Activity {
EditText txtPassword=null;
EditText txtUsername=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_confirmation);
}
public static final class menu2 {
public static final int confirmation=0x7f080000;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(menu2.confirmation, menu);
return true;
}
public void btnCancel_ClickHandler(View arg)
{
finish();
}
public void btnOk_ClickHandler(View arg)
{
txtUsername=(EditText)findViewById(com.example.androidhive.R.id.txtUserName);
txtPassword=(EditText)findViewById(com.example.androidhive.R.id.txtPassword);
if(txtUsername.getText().length()==0)
{
Toast.makeText(getApplicationContext(),
"User name can not be empty.", Toast.LENGTH_LONG).show();
return;
}
if(txtPassword.getText().length()==0)
{
Toast.makeText(getApplicationContext(),
"Password can not be empty.", Toast.LENGTH_LONG).show();
return;
}
Intent intent=new Intent();
intent.putExtra("RESULT_STRING",txtUsername.getText()+ ":"+txtPassword.getText());
setResult(RESULT_OK, intent);
finish();
}
}
Android Manifest.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidhive"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8"
android:targetSdkVersion="18"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:label="#string/app_name"
android:name=".DashboardActivity" >
</activity>
<!-- Confirmation Activity -->
<activity
android:label="Confiramtion Activity"
android:name=".ConfiramtionActivity"></activity>
<!-- Login Activity -->
<activity
android:label="Login Account"
android:name=".LoginActivity"></activity>
<!-- Register Activity -->
<activity
android:label="Register New Account"
android:name=".RegisterActivity">
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Android Fatal Error PLeaseeee Help:-
11-15 16:55:40.948: E/AndroidRuntime(858): FATAL EXCEPTION: main
11-15 16:55:40.948: E/AndroidRuntime(858): android.os.NetworkOnMainThreadException
11-15 16:55:40.948: E/AndroidRuntime(858): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
11-15 16:55:40.948: E/AndroidRuntime(858): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
11-15 16:55:40.948: E/AndroidRuntime(858): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
11-15 16:55:40.948: E/AndroidRuntime(858): at libcore.io.IoBridge.connect(IoBridge.java:112)
11-15 16:55:40.948: E/AndroidRuntime(858): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
11-15 16:55:40.948: E/AndroidRuntime(858): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
11-15 16:55:40.948: E/AndroidRuntime(858): at java.net.Socket.connect(Socket.java:842)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
11-15 16:55:40.948: E/AndroidRuntime(858): at com.example.androidhive.library.JSONParser.getJSONFromUrl(JSONParser.java:47)
11-15 16:55:40.948: E/AndroidRuntime(858): at com.example.androidhive.library.UserFunctions.loginUser(UserFunctions.java:32)
11-15 16:55:40.948: E/AndroidRuntime(858): at com.example.androidhive.LoginActivity$1.onClick(LoginActivity.java:61)
11-15 16:55:40.948: E/AndroidRuntime(858): at android.view.View.performClick(View.java:4240)
11-15 16:55:40.948: E/AndroidRuntime(858): at android.view.View$PerformClick.run(View.java:17721)
11-15 16:55:40.948: E/AndroidRuntime(858): at android.os.Handler.handleCallback(Handler.java:730)
11-15 16:55:40.948: E/AndroidRuntime(858): at android.os.Handler.dispatchMessage(Handler.java:92)
11-15 16:55:40.948: E/AndroidRuntime(858): at android.os.Looper.loop(Looper.java:137)
11-15 16:55:40.948: E/AndroidRuntime(858): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-15 16:55:40.948: E/AndroidRuntime(858): at java.lang.reflect.Method.invokeNative(Native Method)
11-15 16:55:40.948: E/AndroidRuntime(858): at java.lang.reflect.Method.invoke(Method.java:525)
11-15 16:55:40.948: E/AndroidRuntime(858): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-15 16:55:40.948: E/AndroidRuntime(858): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-15 16:55:40.948: E/AndroidRuntime(858): at dalvik.system.NativeStart.main(Native Method)
This exception is thrown when application tries to access network in main thread. This is forbidden as accessing resources over network may take indefinite amount of time and your main thread will be blocked untill network operation finishes, thus making your app frozen to the user.
Instead in your onClick() method you should start a new AsyncTask which will do the networking. After the task finishes proceed with updating the ui (changing activity etc.).

Cannot Resolve NullPointerException On Service Class

I have been tasked to resolve an issue for a group project at my university however I cannot seem to resolve an issue with a NullPointerException in my service class. Our goal is to create a script which continually monitors the android history until it finds a match - then executes a warning class if the service class finds a match in the browser history. The issue occurs on line 71 (of service class) however I do not know how to resolve the issue.
Service Class:
public class Service_class extends Service {
String Dirty1 = "www.pornhub.com";
String Dirty2 = "www.playboy.com";
String Dirty3 = "www.playboy.com";
String Dirty4 = "www.playboy.com";
String Dirty5 = "www.playboy.com";
String Dirty6 = "www.playboy.com";
String Dirty7 = "www.playboy.com";
String Dirty8 = "www.playboy.com";
String Dirty9 = "www.playboy.com";
String Dirty10 = "www.playboy.com";
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onCreate() {
super.onCreate();
TextView tv = (TextView) findViewById(R.id.hello);
String[] projection = new String[] { Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.URL };
Cursor cursor = managedQuery(android.provider.Browser.BOOKMARKS_URI,
projection, null, null, null);
String urls = "";
if (cursor.moveToFirst()) {
String url1 = null;
String url2 = null;
do {
String url = cursor.getString(cursor.getColumnIndex(Browser.BookmarkColumns.URL));
if (url.toLowerCase().contains(Dirty1)) {
} else if (url.toLowerCase().contains(Dirty2)) {
} else if (url.toLowerCase().contains(Dirty3)) {
} else if (url.toLowerCase().contains(Dirty4)) {
} else if (url.toLowerCase().contains(Dirty5)) {
} else if (url.toLowerCase().contains(Dirty6)) {
} else if (url.toLowerCase().contains(Dirty7)) {
} else if (url.toLowerCase().contains(Dirty8)) {
} else if (url.toLowerCase().contains(Dirty9)) {
} else if (url.toLowerCase().contains(Dirty10)) {
//if (url.toLowerCase().contains(Filthy)) {
urls = urls
+ cursor.getString(cursor.getColumnIndex(Browser.BookmarkColumns.TITLE)) + " : "
+ url + "\n";
Intent intent = new Intent(Service_class.this, Warning.class);
Service_class.this.startActivity(intent);
}
} while (cursor.moveToNext());
// tv.setText(urls);
}
}
private void setContentView(int main3) {
// TODO Auto-generated method stub
}
private TextView findViewById(int hello) {
// TODO Auto-generated method stub
return null;
}
private Cursor managedQuery(Uri bookmarksUri, String[] projection,
Object object, Object object2, Object object3) {
// TODO Auto-generated method stub
return null;
}}
Main.java
import java.util.Calendar;
import com.parse.ParseAnalytics;
import com.parse.ParseObject;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.TrafficStats;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.TextView;
public class Main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main3);
// Start service using AlarmManager
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(Main.this, Service_class.class);
PendingIntent pintent = PendingIntent.getService(Main.this, 0, intent,
0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
36000 * 1000, pintent);
// click listener for the button to start service
Button btnStart = (Button) findViewById(R.id.button1);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(getBaseContext(), Service_class.class));
}
});
// click listener for the button to stop service
Button btnStop = (Button) findViewById(R.id.button2);
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(getBaseContext(), Service_class.class));
}
});
}}
LOGCAT:
04-15 13:58:49.980: D/AndroidRuntime(1994): Shutting down VM
04-15 13:58:50.000: W/dalvikvm(1994): threadid=1: thread exiting with uncaught exception (group=0x40cc7930)
04-15 13:58:50.000: E/AndroidRuntime(1994): FATAL EXCEPTION: main
04-15 13:58:50.000: E/AndroidRuntime(1994): java.lang.RuntimeException: Unable to create service com.nfc.linked.Service_class: java.lang.NullPointerException
04-15 13:58:50.000: E/AndroidRuntime(1994): at android.app.ActivityThread.handleCreateService(ActivityThread.java:2539)
04-15 13:58:50.000: E/AndroidRuntime(1994): at android.app.ActivityThread.access$1600(ActivityThread.java:141)
04-15 13:58:50.000: E/AndroidRuntime(1994): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
04-15 13:58:50.000: E/AndroidRuntime(1994): at android.os.Handler.dispatchMessage(Handler.java:99)
04-15 13:58:50.000: E/AndroidRuntime(1994): at android.os.Looper.loop(Looper.java:137)
04-15 13:58:50.000: E/AndroidRuntime(1994): at android.app.ActivityThread.main(ActivityThread.java:5041)
04-15 13:58:50.000: E/AndroidRuntime(1994): at java.lang.reflect.Method.invokeNative(Native Method)
04-15 13:58:50.000: E/AndroidRuntime(1994): at java.lang.reflect.Method.invoke(Method.java:511)
04-15 13:58:50.000: E/AndroidRuntime(1994): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-15 13:58:50.000: E/AndroidRuntime(1994): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-15 13:58:50.000: E/AndroidRuntime(1994): at dalvik.system.NativeStart.main(Native Method)
04-15 13:58:50.000: E/AndroidRuntime(1994): Caused by: java.lang.NullPointerException
04-15 13:58:50.000: E/AndroidRuntime(1994): at com.nfc.linked.Service_class.onCreate(Service_class.java:71)
04-15 13:58:50.000: E/AndroidRuntime(1994): at android.app.ActivityThread.handleCreateService(ActivityThread.java:2529)
04-15 13:58:50.000: E/AndroidRuntime(1994): ... 10 more
04-15 14:00:23.770: D/AndroidRuntime(2047): Shutting down VM
04-15 14:00:23.770: W/dalvikvm(2047): threadid=1: thread exiting with uncaught exception (group=0x40cc7930)
Your method managedQuery() returns null
private Cursor managedQuery(Uri bookmarksUri, String[] projection,
Object object, Object object2, Object object3) {
// TODO Auto-generated method stub
return null;
}}
So when you try to execute a method on null you will get a NullPointerException.
Cursor cursor = managedQuery(android.provider.Browser.BOOKMARKS_URI,
projection, null, null, null); // cursor will be null
String urls = "";
if (cursor.moveToFirst()) { // this will be NPE
Make your managedQuery() method return an instantiated Cursor object.

Categories