Thanks to the replies on NFC and a few certain things, I've understood and managed to compile a code in which the users will be able to read a tag, and if the tag contains a string that is similar to my code, a coupon will be added (image changes) and an integer goes up by 1. This integer will be saved by SharedPreferences and it is used to determine how many coupons the users have collected and show it onResume.
However, after compiling, when I try to run it, my application stops immediately. Can someone help me check on what I may have go wrong? I know it's kinda long but I really have no idea what went wrong.
#TargetApi(10)
//I have to use this line of code because I'm targetted to code at API 8 but some NFC functionalities that I use requires API 10.
public class CouponManager extends Activity {
private static final String TAG = "NFCReadTag";
private NfcAdapter mNfcAdapter;
private IntentFilter[] mNdefExchangeFilters;
private PendingIntent mNfcPendingIntent;
public static final String PREF_FILE_NAME = "PrefFile";
private int[] images = new int[10];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.coupon_layout);
//List of images
images[0]=R.drawable.cp0;
images[1]=R.drawable.cp1;
images[2]=R.drawable.cp2;
images[3]=R.drawable.cp3;
images[4]=R.drawable.cp4;
images[5]=R.drawable.cp5;
images[6]=R.drawable.cp6;
images[7]=R.drawable.cp7;
images[8]=R.drawable.cp8;
images[9]=R.drawable.cp9;
images[10]=R.drawable.cp10;
//Restore preferences
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
//Image to use depending on coupon collected
final ImageView img = new ImageView(this);
if(storedPreference!=10)
{
img.setImageResource(images[storedPreference]);
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setTitle("Redeem Your Coupon?");
builder.setInverseBackgroundForced(true);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", 0); // value to store
editor.commit();
img.setImageResource(images[0]);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
img.setImageResource(images[10]);
}
});
}
//Check and send Intent from NFC tag discovered
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
mNfcPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TOP), 0);
IntentFilter coupontag = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
coupontag.addDataScheme("http");
coupontag.addDataAuthority("www.ichatime.com", null);
coupontag.addDataPath(".*", PatternMatcher.PATTERN_SIMPLE_GLOB);
mNdefExchangeFilters = new IntentFilter[] { coupontag };
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onResume() {
super.onResume();
if(mNfcAdapter != null) {
mNfcAdapter.enableForegroundDispatch(this, mNfcPendingIntent,
mNdefExchangeFilters, null);
} else {
Toast.makeText(getApplicationContext(), "Sorry, No NFC Adapter found.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onPause() {
super.onPause();
if(mNfcAdapter != null) mNfcAdapter.disableForegroundDispatch(this);
}
#Override
protected void onStop() {
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
NdefMessage[] messages = null;
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if (rawMsgs != null) {
messages = new NdefMessage[rawMsgs.length];
for (int i = 0; i < rawMsgs.length; i++) {
messages[i] = (NdefMessage) rawMsgs[i];
}
}
if(messages[0] != null) {
String result="";
byte[] payload = messages[0].getRecords()[0].getPayload();
// this assumes that we get back am SOH followed by host/code
for (int b = 1; b<payload.length; b++) { // skip SOH
result += (char) payload[b];
}
if (result == "ichatime.com")
{
final ImageView img = new ImageView(this);
Toast.makeText(getApplicationContext(), "Coupon collected!", Toast.LENGTH_SHORT).show();
if (storedPreference!=10)
{
storedPreference++;
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference);
img.setImageResource(images[storedPreference]);
}
if (storedPreference==10)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setTitle("Redeem Your Coupon?");
builder.setInverseBackgroundForced(true);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", 0); // value to store
editor.commit();
img.setImageResource(images[0]);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
img.setImageResource(images[10]);
}
});
}
else
{
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", 10);
img.setImageResource(images[10]);
}}
else
{
Toast.makeText(getApplicationContext(), "Wrong tag detected!", Toast.LENGTH_SHORT).show();
}
//Debugging Mode to see what is contained in the tags.
// Toast.makeText(getApplicationContext(), "Tag Contains " + result, Toast.LENGTH_SHORT).show();
}
}
}
}
Logcat errors:
>11-26 01:16:11.869: D/AndroidRuntime(550): Shutting down VM
>
11-26 01:16:11.869: W/dalvikvm(550): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
>
11-26 01:16:11.929: I/dalvikvm(550): threadid=3: reacting to signal 3
>
11-26 01:16:11.979: E/AndroidRuntime(550): FATAL EXCEPTION: main
>
**11-26 01:16:11.979: E/AndroidRuntime(550): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ponpon/com.example.ponpon.MainActivity}: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ponpon/com.example.ponpon.CouponManager}: java.lang.ArrayIndexOutOfBoundsException: length=10; index=10**
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.ActivityThread.access$600(ActivityThread.java:123)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.os.Handler.dispatchMessage(Handler.java:99)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.os.Looper.loop(Looper.java:137)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.ActivityThread.main(ActivityThread.java:4424)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at java.lang.reflect.Method.invokeNative(Native Method)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at java.lang.reflect.Method.invoke(Method.java:511)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at dalvik.system.NativeStart.main(Native Method)
>
11-26 01:16:11.979: E/AndroidRuntime(550): Caused by: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ponpon/com.example.ponpon.CouponManager}: java.lang.ArrayIndexOutOfBoundsException: length=10; index=10
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.ActivityThread.startActivityNow(ActivityThread.java:1797)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:135)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:347)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:682)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.widget.TabHost.setCurrentTab(TabHost.java:346)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.widget.TabHost.addTab(TabHost.java:236)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at com.example.ponpon.MainActivity.onCreate(MainActivity.java:37)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.Activity.performCreate(Activity.java:4465)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
>
11-26 01:16:11.979: E/AndroidRuntime(550): ... 11 more
>
11-26 01:16:11.979: E/AndroidRuntime(550): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=10; index=10
>
11-26 01:16:11.979: E/AndroidRuntime(550): at com.example.ponpon.CouponManager.onCreate(CouponManager.java:53)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.Activity.performCreate(Activity.java:4465)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
>
11-26 01:16:11.979: E/AndroidRuntime(550): ... 21 more
What did I do wrong with my arrays? Thanks for the clarification guys!
Your logcat is printing an ArrayOutOfBounds exception on your onCreate method.
The problem is that you are declaring a 10 items sized array, and then trying to put 11 items on it.
You have to declare a new int[11] array.
I seem to have solved the problem by adding the array count by 1. What I don't understand is, I want to keep 11 items in the array so isn't
private int[] images = new int[10] enough?
Cause from what I understand, int[0] keeps the first value, hence int[10] will keep the eleventh value? Thank you guys!
Related
I was using an integer for the money factor in this little test app but I realized that long was more appropriate and I changed the code so that money is a long instead of an int and I changed SharedPreferences appropriately as well, however it does not work wheras it did when I used int. Thank you for the help!
public class Home extends AppCompatActivity {
SharedPreferences pref;
SharedPreferences.Editor editor;
Intent intent;
TextView home_money_view;
long money; // this is the variable that is causing problems
int initial;
final long TEST = (long)-1;
int gold_pieces;
int gold_price = 50;
TimerTask timerTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
home_money_view = (TextView) findViewById(R.id.home_money_view)
pref = getApplicationContext().getSharedPreferences("MY_PREFS", MODE_PRIVATE);
editor = pref.edit();
money = pref.getLong("temp_money",Long.MIN_VALUE); // get value
if (money==Long.MIN_VALUE){
money=0;
}
gold_pieces = pref.getInt("temp_gold",-1);
if (gold_pieces==-1){
gold_pieces=0;
}
initial = pref.getInt("initial",0);
money+=initial;
editor.putInt("initial",0);
editor.commit();
home_money_view = (TextView) findViewById(R.id.home_money_view);
home_money_view.setText(money+"");
editor.commit();
}
public void backToSplash(View view){
intent = new Intent(Home.this,BusinessSelector.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
public void goToSecondView(View view){
long temp_money = money;
editor.putLong("temp_money",temp_money); // set value
int temp_gold = gold_pieces;
editor.putInt("temp_gold",temp_gold);
editor.commit();
intent = new Intent(Home.this,SecondView.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
public void goToOtherView(View view) {
long temp_money = money;
editor.putLong("temp_money",temp_money); // set value
int temp_gold = gold_pieces;
editor.putInt("temp_gold", temp_gold);
editor.commit();
intent = new Intent(Home.this, Next.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
Logcat:
04-13 19:01:03.675 12896-12896/com.exampleryancocuzzo.ryan.markettycoon E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.exampleryancocuzzo.ryan.markettycoon/com.exampleryancocuzzo.ryan.markettycoon.Home}: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
at android.app.SharedPreferencesImpl.getLong(SharedPreferencesImpl.java:228)
at com.exampleryancocuzzo.ryan.markettycoon.Home.onCreate(Home.java:56)
at android.app.Activity.performCreate(Activity.java:4466)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
I switched from running my app on a phone to a nexus 10 tablet and now it says "unfortunately the application has stopped."
The tablet is running 4.4.2, my target api is set to 19 in the manifest.
When I run it in debug mode I get Source Not Found. I tried clicking edit source lookup path and adding my project and had no luck.
I've looked all over the internet and haven't had any luck solving this problem. Any suggestions would be a big help.
"java.lang.RuntimeException: Unable to start activity ComponentInfo{com.looper.video/com.looper.video.MainActivity}: java.lang.NullPointerException"
Edit:
MainActivity:
package com.looper.video;
public class MainActivity extends Activity {
private VideoView video;
private MediaController ctlr;
final Uri firstVideoPath = Uri.parse("android.resource://com.looper.video/" + R.raw.wildlife);
final Uri secondVideoPath = Uri.parse("android.resource://com.looper.video/" + R.raw.wildlife1);
private String videosPath = Environment.getExternalStorageDirectory() + "/videos/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File folder = new File(videosPath);
File[] customFiles = folder.listFiles();
List<String> customFileNames = new ArrayList<String>();
for(File file : customFiles) {
customFileNames.add(file.getName());
}
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, customFileNames);
spinnerArrayAdapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
Spinner spinner = (Spinner)findViewById(R.id.spinnerCustomFiles);
spinner.setAdapter(spinnerArrayAdapter);
video = (VideoView)findViewById(R.id.videoView1);
ctlr = new MediaController(this);
final Button firstVideoBtn = (Button) findViewById(R.id.firstVideoBtn);
firstVideoBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
playFirstVideo();
}
});
final Button secondVideoBtn = (Button) findViewById(R.id.secondVideoBtn);
secondVideoBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
playSecondVideo();
}
});
}
public void playFeatured(View v) {
try {
Spinner spinner = (Spinner)findViewById(R.id.spinnerCustomFiles);
String strPath = videosPath + spinner.getSelectedItem().toString();
Toast.makeText(this, strPath, Toast.LENGTH_LONG).show();
//Uri path = Uri.parse(videosPath + spinner.getSelectedItem().toString());
video.setVideoPath(strPath);
ctlr.setMediaPlayer(video);
video.setMediaController(ctlr);
video.requestFocus();
video.start();
video.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer vmp) {
playSecondVideo();
}
});
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
public void playFirstVideo() {
video.setVideoURI(firstVideoPath);
ctlr.setMediaPlayer(video);
video.setMediaController(ctlr);
video.requestFocus();
video.start();
video.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer vmp) {
playSecondVideo();
}
});
}
public void playSecondVideo() {
SharedPreferences sp = getSharedPreferences("schedule", Context.MODE_PRIVATE);
//SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
String startTime = sp.getString("startTime", "");
String endTime = sp.getString("endTime", "");
/*
//SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
//Date dateStartTime = parser.parse(startTime);
//Date dateEndTime = parser.parse(endTime);
Date now = new Date();
try {
if (userDate.after(ten) && userDate.before(eighteen)) {
}
} catch (ParseException e) {
// Invalid date was entered
}
System.out.println("Now:"+now);
System.out.println("Start"+startTime);
System.out.println("End:"+endTime);
//if(now.before(dateEndTime) && now.after(dateStartTime)){
//disableAll();
//} else {
*
*/
video.setVideoURI(secondVideoPath);
ctlr.setMediaPlayer(video);
video.setMediaController(ctlr);
video.requestFocus();
video.start();
video.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer vmp) {
playSecondVideo();
}
});
//}
}
public void admin(View view)
{
//MySQLiteHelper db = new MySQLiteHelper(this);
//final String password = db.getUser(7).getPassword();
//db.close();
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
final EditText pass = new EditText(this);
alert.setView(pass);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = pass.getText().toString().trim();
SharedPreferences sp1 = getSharedPreferences("Login", 0);
//String username = sp1.getString("UserName", "");
String password = sp1.getString("Password", "");
if(value.equals(password)) {
Intent intent = new Intent(getBaseContext(),Admin.class);
startActivity(intent);
}
//Toast.makeText(getApplicationContext(), password + " " + value, Toast.LENGTH_SHORT).show();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
alert.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;
}
#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 disableAll(){
Button firstVideoBtn = (Button)findViewById(R.id.firstVideoBtn);
firstVideoBtn.setEnabled(false);
Button secondVideoBtn = (Button)findViewById(R.id.secondVideoBtn);
secondVideoBtn.setEnabled(false);
Spinner spinner = (Spinner)findViewById(R.id.spinnerCustomFiles);
spinner.setEnabled(false);
Button btnPlay = (Button)findViewById(R.id.btnPlayFeatured);
btnPlay.setEnabled(false);
VideoView videoView = (VideoView)findViewById(R.id.videoView1);
videoView.setEnabled(false);
}
}
Full logcat:
D/dalvikvm(2817): GC_FOR_ALLOC freed 58K, 4% free 3441K/3568K, paused 20ms, total 20ms
10-08 15:23:17.965: D/dalvikvm(2817): GC_FOR_ALLOC freed 2K, 4% free 3505K/3632K, paused 7ms, total 7ms
10-08 15:23:17.975: I/dalvikvm-heap(2817): Grow heap (frag case) to 8.739MB for 5515216-byte allocation
10-08 15:23:17.985: D/dalvikvm(2817): GC_FOR_ALLOC freed <1K, 2% free 8891K/9020K, paused 7ms, total 7ms
10-08 15:23:18.055: D/AndroidRuntime(2817): Shutting down VM
10-08 15:23:18.055: W/dalvikvm(2817): threadid=1: thread exiting with uncaught exception (group=0x4155eba8)
10-08 15:23:18.055: E/AndroidRuntime(2817): FATAL EXCEPTION: main
10-08 15:23:18.055: E/AndroidRuntime(2817): Process: com.looper.video, PID: 2817
10-08 15:23:18.055: E/AndroidRuntime(2817): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.looper.video/com.looper.video.MainActivity}: java.lang.NullPointerException
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.ActivityThread.access$800(ActivityThread.java:135)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.os.Handler.dispatchMessage(Handler.java:102)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.os.Looper.loop(Looper.java:136)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.ActivityThread.main(ActivityThread.java:5017)
10-08 15:23:18.055: E/AndroidRuntime(2817): at java.lang.reflect.Method.invokeNative(Native Method)
10-08 15:23:18.055: E/AndroidRuntime(2817): at java.lang.reflect.Method.invoke(Method.java:515)
10-08 15:23:18.055: E/AndroidRuntime(2817): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
10-08 15:23:18.055: E/AndroidRuntime(2817): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
10-08 15:23:18.055: E/AndroidRuntime(2817): at dalvik.system.NativeStart.main(Native Method)
10-08 15:23:18.055: E/AndroidRuntime(2817): Caused by: java.lang.NullPointerException
10-08 15:23:18.055: E/AndroidRuntime(2817): at com.looper.video.MainActivity.onCreate(MainActivity.java:52)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.Activity.performCreate(Activity.java:5231)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
10-08 15:23:18.055: E/AndroidRuntime(2817): ... 11 more
I am very new to android. I have a counter on some SomeActivity, but when I get to the page corresponding to SomeActivity, my app crashes :
final TextView counter = (TextView) findViewById(R.id.laws_counter);
ImageView handDown = (ImageView) findViewById(R.id.handViewDown);
counter.setText("" + 0);
I want that on click of the handown, the counter is idented by -1. Here's
handDown.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(NewsActivity.this,
"The favorite list would appear on clicking this icon",
Toast.LENGTH_LONG).show();
setDown();
}
private void setDown() {
String count = counter.getText().toString();
int now_count = Integer.parseInt(count) +1;
counter.setText(String.valueOf(now_count));
}
});
Is this code correct ?
Update : here's the logcat
10-22 00:18:05.579: ERROR/AndroidRuntime(378): FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.donnfelker.android.bootstrap/com.donnfelker.android.bootstrap.ui.NewsActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
at android.app.ActivityThread.access$1500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.donnfelker.android.bootstrap.ui.NewsActivity.onCreate(NewsActivity.java:41)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
... 11 more
There are many ways that you can implement that functionality but think this would be an easy solution.
Make a helper method:
public class PreferencesData {
public static void saveInt(Context context, String key, int value) {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context);
sharedPrefs.edit().putInt(key, value).commit();
}
public static int getInt(Context context, String key, int defaultValue) {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context);
return sharedPrefs.getInt(key, defaultValue);
}
}
Then simply call the putInt method to save the counter in any Activity and getInt to get it again in any other Activity. As long as you use the same key both places.
I am creating a simple Click Counter Android App using Java. I am new to Java. Here is my code below, the gui has different buttons with different functions, for example the count button itself, a reset count button, and a mute sound button.
public class wazeefa extends Activity {
//Count Button
TextView txtCount;
ImageView image;
Button btnCount;
Button wmute;
Button wreset;
public static int count=0;
SharedPreferences app_preferences;
MediaPlayer mpButtonClick;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// The activity is being created.
setContentView(R.layout.wazeefa);
//SAVE COUNT
app_preferences = this.getSharedPreferences("myPrefscount", MODE_WORLD_READABLE);
count = app_preferences.getInt("count", 0);
txtCount = (TextView)findViewById(R.id.wcount);
txtCount.setText("This app has been started " + count + " times.");
txtCount = (TextView)findViewById(R.id.wcount);
txtCount.setText("This app has been started " + count + " times.");
//Button SOUND AND COUNT
mpButtonClick = MediaPlayer.create(this, R.raw.bubble);
//RESET Button
wreset = (Button)findViewById(R.id.wreset);
txtCount = (TextView)findViewById(R.id.wcount);
txtCount.setText(String.valueOf(count));
btnCount = (Button)findViewById(R.id.wclick);
btnCount.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
image = (ImageView) findViewById(R.id.imageview);
count++;
if (count > 50) count = 0; image.setImageResource(R.drawable.duroodimage);
if (count > 0) image.setImageResource(R.drawable.duroodimage);
if (count > 9) image.setImageResource(R.drawable.zikrimage);
if (count > 39) image.setImageResource(R.drawable.duroodimage);
txtCount.setText(String.valueOf(count));
}
});
wreset.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
count = 0;
image.setImageResource(R.drawable.duroodimage);;
txtCount.setText("0");
}
});
}
#Override
protected void onPause() {
super.onPause();
// save count value here
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("count", count);
editor.commit();
}
//MUTE button
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.wmute:
AudioManager.setMode(AudioManager.MODE_IN_CALL);
AudioManager.setStreamSolo(AudioManager.STREAM_VOICE_CALL, true);
default:
AudioManager.setMode(AudioManager.MODE_NORMAL );
AudioManager.setStreamSolo(AudioManager.STREAM_VOICE_CALL, false);
break;
}
}
I have 1 issue:
When I go back into the app and the count shows as '5' just for example, the Reset button no longer functions - it does nothing, I get an error message on AVD saying 'unfortunately 'App' has stopped'. But when I continue the count and then hit the Reset button it works changes the count to zero again
Any suggestions on the above issue, have I missed anything or placed code in the wrong areas? The button sound was working before I edited the code, to save the 'count' data.
Let me know if I'm being vague...
The Crash Log:
12-24 18:07:42.661: W/Trace(3633): Unexpected value from nativeGetEnabledTags: 0
12-24 18:07:42.741: D/AndroidRuntime(3633): Shutting down VM
12-24 18:07:42.741: W/dalvikvm(3633): threadid=1: thread exiting with uncaught exception (group=0x40a70930)
12-24 18:07:42.811: E/AndroidRuntime(3633): FATAL EXCEPTION: main
12-24 18:07:42.811: E/AndroidRuntime(3633): java.lang.NullPointerException
12-24 18:07:42.811: E/AndroidRuntime(3633): at com.shaadcorp.wazaifapp.wazeefa$2.onClick(wazeefa.java:81)
12-24 18:07:42.811: E/AndroidRuntime(3633): at android.view.View.performClick(View.java:4202)
12-24 18:07:42.811: E/AndroidRuntime(3633): at android.view.View$PerformClick.run(View.java:17340)
12-24 18:07:42.811: E/AndroidRuntime(3633): at android.os.Handler.handleCallback(Handler.java:725)
12-24 18:07:42.811: E/AndroidRuntime(3633): at android.os.Handler.dispatchMessage(Handler.java:92)
12-24 18:07:42.811: E/AndroidRuntime(3633): at android.os.Looper.loop(Looper.java:137)
12-24 18:07:42.811: E/AndroidRuntime(3633): at android.app.ActivityThread.main(ActivityThread.java:5039)
12-24 18:07:42.811: E/AndroidRuntime(3633): at java.lang.reflect.Method.invokeNative(Native Method)
12-24 18:07:42.811: E/AndroidRuntime(3633): at java.lang.reflect.Method.invoke(Method.java:511)
12-24 18:07:42.811: E/AndroidRuntime(3633): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-24 18:07:42.811: E/AndroidRuntime(3633): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-24 18:07:42.811: E/AndroidRuntime(3633): at dalvik.system.NativeStart.main(Native Method)
12-24 18:07:48.842: I/Process(3633): Sending signal. PID: 3633 SIG: 9
12-24 18:07:51.572: E/Trace(3808): error opening trace file: No such file or directory (2)
I guess I didn't see mpButtonClick.start() anywhere in your code. That's why sound is not playing. Add mpButtonClick.start(). to your ClickListener.
fixed issue, thanks for your help Passionate Androiden.
public class wazeefa extends Activity {
//Count Button
TextView txtCount;
ImageView image;
Button btnCount;
Button wmute;
Button wreset;
public static int count=0;
SharedPreferences app_preferences;
MediaPlayer mpButtonClick;
AudioManager audioManager;
public static boolean mutestatus=false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// The activity is being created.
setContentView(R.layout.wazeefa);
audioManager =
(AudioManager)getSystemService(Context.AUDIO_SERVICE);
//SAVE COUNT
app_preferences = this.getSharedPreferences("myPrefscount", MODE_WORLD_READABLE);
count = app_preferences.getInt("count", 0);
txtCount = (TextView)findViewById(R.id.wcount);
txtCount.setText("This app has been started " + count + " times.");
image = (ImageView) findViewById(R.id.imageview);
txtCount = (TextView)findViewById(R.id.wcount);
txtCount.setText("This app has been started " + count + " times.");
//Button SOUND AND COUNT
mpButtonClick = MediaPlayer.create(this, R.raw.bubble);
//RESET Button
wreset = (Button)findViewById(R.id.wreset);
txtCount = (TextView)findViewById(R.id.wcount);
txtCount.setText(String.valueOf(count));
btnCount = (Button)findViewById(R.id.wclick);
wmute=(Button)findViewById(R.id.wmute);
btnCount.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
count++;
if (count > 50) count = 0; image.setImageResource(R.drawable.duroodimage);
if (count > 0) image.setImageResource(R.drawable.duroodimage);
if (count > 9) image.setImageResource(R.drawable.zikrimage);
if (count > 39) image.setImageResource(R.drawable.duroodimage);
txtCount.setText(String.valueOf(count));
mpButtonClick.start();
}
});
wreset.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
count = 0;
image.setImageResource(R.drawable.duroodimage);;
txtCount.setText("0");
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("count", count);
editor.commit();
}
});
wmute.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(!mutestatus){
mutestatus=true;
audioManager.setMode(AudioManager.MODE_IN_CALL);
audioManager.setStreamSolo(AudioManager.STREAM_VOICE_CALL, true);
Log.v("'test....",""+mutestatus);
}
else{
mutestatus=false;
audioManager.setMode(AudioManager.MODE_NORMAL );
audioManager.setStreamSolo(AudioManager.STREAM_VOICE_CALL, false);
Log.v("'test....",""+mutestatus);
}
}});
}
#Override
protected void onPause() {
super.onPause();
// save count value here
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("count", count);
editor.commit();
}
}
I am trying to work on my android project but getting a null pointer exception in my main function.
So, based on the input id, i wish to set the id entered from the editText and retrieve it when i call the get function which will complete my where clause for the condition.
here is my code:
/*---GetSet.java ---- */
public class GetSet {
long gwid=0;
public void setId(long id)
{
gwid = id;
}
public long getId()
{
return gwid;
}
}
The following is my MainActivity.java file
public class MainActivity extends Activity {
EditText etGWid;
Button OKbtn;
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etGWid = (EditText)findViewById(R.id.etGWID);
OKbtn = (Button)findViewById(R.id.OKbtn);
final GetSet obj_getset = null;
final SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
// Create a shared preferences variable using the SharedPreferenceManager for storing GWids
SharedPreferences.Editor editor = app_preferences.edit(); // We also need a shared preferences editor to handle the shared preference requests
// Call the edit method (library function) to editor variable can edit the key, values.
editor.putInt("47688507", 47688507); // put in the shared preferences values of user GWids and give them a key for retrieval purposes
editor.putInt("1234567", 1234567);
editor.putInt("7654321", 7654321);
editor.commit(); //commit is necessary to save the shared preferences
OKbtn.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("null")
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String gwidCheck = etGWid.getText().toString(); //get the value user enters for GWid
if(app_preferences.contains(gwidCheck)) // this will check the stored shared preferences and compare with the value entered
{
Context context = getApplicationContext();
CharSequence text = "Login Successfull";
int duration = Toast.LENGTH_SHORT; //If it exists, then create a toast message for success
//etGWid.setText(""); // make the textbox empty
long setid = Long.parseLong(gwidCheck); // take the string gwid and convert to long
obj_getset.setId(setid); // set the gwid entered
Toast toast = Toast.makeText(context, text, duration);
toast.show();
intentfunction();
}
else
{
Context context = getApplicationContext();
CharSequence text = "Login Failed"; // If doesnt exist, create a toast for fail
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
});
}
private void intentfunction()
{
Intent intent = new Intent(this, SelectOptions.class);
//editText = (EditText) findViewById(R.id.editText1);
//editText = new EditText(this);
String message = "TestHello";
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Line number 69 is where i get the problem which is the foll line:
obj_getset.setId(setid);
And this is one of a method in MySQLitehelper.java file that is used to retrieve the row based on the id:
public Cursor getRecord(long rowId) throws SQLException
{
Cursor mCursor =
db.query(true, TABLE_NAME, new String[] {COLUMN_ID,
COLUMN_DATE, COLUMN_LOCATION, COLUMN_TIME},
COLUMN_ID + "=" + getset.getId(), null, null, null, null, null);
if (mCursor != null)
{
mCursor.moveToFirst();
}
return mCursor;
}
My Question is, how do I set the value entered by the user so I can get the value and based on that value, I can put the condition in my where clause just like above. Where am I going wrong ?
LogCat
11-29 21:19:22.525: D/AndroidRuntime(10323): Shutting down VM
11-29 21:19:22.525: W/dalvikvm(10323): threadid=1: thread exiting with uncaught exception (group=0x40a70930)
11-29 21:19:22.583: E/AndroidRuntime(10323): FATAL EXCEPTION: main
11-29 21:19:22.583: E/AndroidRuntime(10323): java.lang.NullPointerException
11-29 21:19:22.583: E/AndroidRuntime(10323): at com.example.upd.MainActivity$1.onClick(MainActivity.java:69)
11-29 21:19:22.583: E/AndroidRuntime(10323): at android.view.View.performClick(View.java:4202)
11-29 21:19:22.583: E/AndroidRuntime(10323): at android.view.View$PerformClick.run(View.java:17340)
11-29 21:19:22.583: E/AndroidRuntime(10323): at android.os.Handler.handleCallback(Handler.java:725)
11-29 21:19:22.583: E/AndroidRuntime(10323): at android.os.Handler.dispatchMessage(Handler.java:92)
11-29 21:19:22.583: E/AndroidRuntime(10323): at android.os.Looper.loop(Looper.java:137)
11-29 21:19:22.583: E/AndroidRuntime(10323): at android.app.ActivityThread.main(ActivityThread.java:5039)
11-29 21:19:22.583: E/AndroidRuntime(10323): at java.lang.reflect.Method.invokeNative(Native Method)
11-29 21:19:22.583: E/AndroidRuntime(10323): at java.lang.reflect.Method.invoke(Method.java:511)
11-29 21:19:22.583: E/AndroidRuntime(10323): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
11-29 21:19:22.583: E/AndroidRuntime(10323): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
11-29 21:19:22.583: E/AndroidRuntime(10323): at dalvik.system.NativeStart.main(Native Method)
11-29 21:19:25.702: I/Process(10323): Sending signal. PID: 10323 SIG: 9
Program closes down unexpectedly.
final GetSet obj_getset = null;
Well of course you're getting a nullPointerException; Your obj_getset is defined to be null right there.