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
hi guys i have a problem. when i run my app, one activity crash after i press the buttons x times. sometimes it works, sometimes not. please help. don't know what to do.strong text
08-08 09:19:57.087: E/AndroidRuntime(2772): FATAL EXCEPTION: main
08-08 09:19:57.087: E/AndroidRuntime(2772): Process: org.nolodigas, PID: 2772
08-08 09:19:57.087: E/AndroidRuntime(2772): java.lang.IllegalStateException: Could not execute method of the activity
08-08 09:19:57.087: E/AndroidRuntime(2772): at android.view.View$1.onClick(View.java:3823)
08-08 09:19:57.087: E/AndroidRuntime(2772): at android.view.View.performClick(View.java:4438)
08-08 09:19:57.087: E/AndroidRuntime(2772): at android.view.View$PerformClick.run(View.java:18422)
08-08 09:19:57.087: E/AndroidRuntime(2772): at android.os.Handler.handleCallback(Handler.java:733)
08-08 09:19:57.087: E/AndroidRuntime(2772): at android.os.Handler.dispatchMessage(Handler.java:95)
08-08 09:19:57.087: E/AndroidRuntime(2772): at android.os.Looper.loop(Looper.java:136)
08-08 09:19:57.087: E/AndroidRuntime(2772): at android.app.ActivityThread.main(ActivityThread.java:5017)
08-08 09:19:57.087: E/AndroidRuntime(2772): at java.lang.reflect.Method.invokeNative(Native Method)
08-08 09:19:57.087: E/AndroidRuntime(2772): at java.lang.reflect.Method.invoke(Method.java:515)
08-08 09:19:57.087: E/AndroidRuntime(2772): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-08 09:19:57.087: E/AndroidRuntime(2772): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-08 09:19:57.087: E/AndroidRuntime(2772): at dalvik.system.NativeStart.main(Native Method)
08-08 09:19:57.087: E/AndroidRuntime(2772): Caused by: java.lang.reflect.InvocationTargetException
08-08 09:19:57.087: E/AndroidRuntime(2772): at java.lang.reflect.Method.invokeNative(Native Method)
08-08 09:19:57.087: E/AndroidRuntime(2772): at java.lang.reflect.Method.invoke(Method.java:515)
08-08 09:19:57.087: E/AndroidRuntime(2772): at android.view.View$1.onClick(View.java:3818)
08-08 09:19:57.087: E/AndroidRuntime(2772): ... 11 more
08-08 09:19:57.087: E/AndroidRuntime(2772): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=121; index=123
08-08 09:19:57.087: E/AndroidRuntime(2772): at org.nolodigas.Jugar.okButton(Jugar.java:104)
08-08 09:19:57.087: E/AndroidRuntime(2772): ... 14 more
there is my logcat. i can't find the error . here is my java code
public class Jugar extends Activity implements ViewSwitcher.ViewFactory,
View.OnClickListener {
private TextSwitcher mSwitcher;
TextView textViewTime;
ImageView img;
int cont=0;
private int mCounter = 0;
private int[] a = {
R.drawable.casa,R.drawable.cantar,R.drawable.agua,R.drawable.anciana,R.drawable.arbol,R.drawable.mochila,R.drawable.auto,R.drawable.azucar,R.drawable.libro,R.drawable.empresa,R.drawable.control,R.drawable.computadora,R.drawable.boca,
R.drawable.boliche,R.drawable.campo,R.drawable.cantar,R.drawable.cargador,R.drawable.casa,R.drawable.casamiento,R.drawable.cerveza,R.drawable.cocina,R.drawable.concierto,R.drawable.control,R.drawable.cuaderno,R.drawable.cuerpo,R.drawable.deporte,R.drawable.dj,
R.drawable.doctor,R.drawable.droga,R.drawable.edificio,R.drawable.empresa,R.drawable.escritor,R.drawable.famoso,R.drawable.ganso,R.drawable.gato,R.drawable.gente,R.drawable.ginobili,R.drawable.grande,R.drawable.hospital,R.drawable.hotel,
R.drawable.huerfano,R.drawable.ingeniero,R.drawable.jugo,R.drawable.libreria,R.drawable.libro,R.drawable.mesa,R.drawable.mochila,R.drawable.museo,R.drawable.musica,R.drawable.naranja,R.drawable.nieve,R.drawable.ovni,R.drawable.paris,
R.drawable.pasto,R.drawable.pelo,R.drawable.pelota,R.drawable.pendrive,R.drawable.periodista,R.drawable.perro,R.drawable.piramide,R.drawable.pistola,R.drawable.planeta,R.drawable.playa,R.drawable.sirena,R.drawable.abogado,R.drawable.esqui,R.drawable.funda,R.drawable.disco,
R.drawable.pornografia,R.drawable.profesor,R.drawable.puerta,R.drawable.radio,R.drawable.rio,R.drawable.roma,R.drawable.ropa,R.drawable.sillon,R.drawable.superheroe,R.drawable.taza,R.drawable.luz,R.drawable.lapiz,R.drawable.ron,R.drawable.fernet,R.drawable.bariloche,R.drawable.garage,R.drawable.alarma,
R.drawable.tela,R.drawable.televisor,R.drawable.unia,R.drawable.ventana,R.drawable.ventilador,R.drawable.viajar,R.drawable.zapatillas,R.drawable.pelea,R.drawable.panda,R.drawable.cable,R.drawable.tinelli,R.drawable.manzana,R.drawable.ftutilla,R.drawable.leche,R.drawable.fotocopia,
R.drawable.mono,R.drawable.piano,R.drawable.guitarra,R.drawable.bateria,R.drawable.camara,R.drawable.bombon,R.drawable.tren,R.drawable.pintura,R.drawable.aldea,R.drawable.grito,R.drawable.bandera,R.drawable.messi,R.drawable.aguero,R.drawable.legrand,R.drawable.zuckerberg,R.drawable.billetera,R.drawable.guepardo,R.drawable.elefante,R.drawable.calle,R.drawable.gimnasio,R.drawable.argentina,
};
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.jugar);
mSwitcher = (TextSwitcher) findViewById(R.id.switcher);
mSwitcher.setFactory(this);
textViewTime = (TextView) findViewById(R.id.texto1);
textViewTime.setText("01:00");
Button nextButton = (Button) findViewById(R.id.next);
nextButton.setOnClickListener(this);
updateCounter();
}
private void updateCounter() {
mSwitcher.setText(String.valueOf(mCounter));
}
public View makeView() {
TextView t = new TextView(this);
t.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
t.setTextSize(36);
return t;
}
protected void setOrientation() {
int current = getRequestedOrientation();
// only switch the orientation if not in portrait
if ( current != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT ) {
setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
public void lanzarJugar(View v) {
}
#Override
public void onClick(View v) {
mCounter=0;
mSwitcher.setText(String.valueOf(mCounter));
final CounterClass timer = new CounterClass(60000, 1000);
timer.start();
ImageView img= (ImageView) findViewById(R.id.imageView1);
int rando = (int) (Math.random() * 125);
Drawable d = getResources().getDrawable(a[rando]);
img.setImageDrawable(d);
}
public void noButton(View v){
ImageView img= (ImageView) findViewById(R.id.imageView1);
int rando = (int) (Math.random() * 125);
Drawable d = getResources().getDrawable(a[rando]);
img.setImageDrawable(d);
}
public void okButton(View v) {
ImageView img= (ImageView) findViewById(R.id.imageView1);
int rando = (int) (Math.random() * 125);
Drawable d = getResources().getDrawable(a[rando]);
img.setImageDrawable(d);
mCounter++;
updateCounter();
cont++;
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint({ "NewApi", "DefaultLocale" })
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// TODO Auto-generated constructor stub
}
#SuppressLint("NewApi")
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
long millis = millisUntilFinished;
String ms = String.format("%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
System.out.println(ms);
textViewTime.setText(ms);
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
textViewTime.setText("Tiempo!");
}
}
}
In the code line below, you are generating a random number and picking an Resource Integer. But the index you are trying to get from array doesn't exist. So you are getting IndexOutOfBounds exception.
int rando = (int) (Math.random() * 125);
Drawable d = getResources().getDrawable(a[rando]);
Error is in okButton method here:
int rando = (int) (Math.random() * 125);
Drawable d = getResources().getDrawable(a[rando]);
rando is returning a value out bounds of a array.
Your array contains only 121 elements. Hence, whenever the random number generated is within 0-120 range, the app functions properly. But whenever the number falls between 121-124, it crashes due to IndexOutOfBounds exception. Either add more items to the array or use the following code:
int rando = (int) (Math.random() * 121);
Drawable d = getResources().getDrawable(a[rando]);
I would like to update my Listview in a fragmen in a onPostExecute() separate class.
The first initialization of the the Listview doas work, but wehe I call createList() again, the App crashes (NullPointerException)
Any Idea?
Main_Fragment:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View fragmentView = inflater.inflate(R.layout.main_fragment, container, false);
StartSocketService = (Button) fragmentView.findViewById(R.id.start_socketservice);
StartSocketService.setOnClickListener(this);
StopSocketService = (Button) fragmentView.findViewById(R.id.stop_socketservice);
StopSocketService.setOnClickListener(this);
listview = (ListView) fragmentView.findViewById(R.id.listView1);
createList();
return fragmentView;
}
public void createList(){
//Reading Server IPs from SharedPreferences and put them to ListView
SharedPreferences settings = getActivity().getSharedPreferences("Found_Devices", 0);
for (int i = 0; i < 255; i++) {
if ((settings.getString("Server"+i,null)) != null) {
serverList.add(settings.getString("Server"+i, null));
Log.v("Reading IP: " +settings.getString("Server"+i, null), " from SraredPreferrences at pos.: "+i );
}
}
//Initializing listView
final StableArrayAdapter adapter = new StableArrayAdapter(getActivity(),android.R.layout.simple_list_item_1, serverList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
final String item = (String) parent.getItemAtPosition(position);
view.animate().setDuration(2000).alpha(0).withEndAction(new Runnable() {
#Override
public void run() {
serverList.remove(item);
adapter.notifyDataSetChanged();
view.setAlpha(1);
}
});
}
});
}
Some class:
async_cient = new AsyncTask<Void, Void, Void>() {
...
protected void onPostExecute(Void result) {
Toast.makeText(mContext, "Scan Finished", Toast.LENGTH_SHORT).show();
Main_Fragment cList = new Main_Fragment();
cList.createList();
super.onPostExecute(result);
}
};
Log:
07-29 14:42:46.428 3382-3382/de.liquidbeam.LED.control D/AndroidRuntime﹕ Shutting down VM
07-29 14:42:46.428 3382-3382/de.liquidbeam.LED.control W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41549ba8)
07-29 14:42:46.438 3382-3382/de.liquidbeam.LED.control E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: de.liquidbeam.LED.control, PID: 3382
java.lang.NullPointerException
at de.liquidbeam.LED.control.fragments.Main_Fragment.createList(Main_Fragment.java:56)
at de.liquidbeam.LED.control.background.UDP_Discover$1.onPostExecute(UDP_Discover.java:94)
at de.liquidbeam.LED.control.background.UDP_Discover$1.onPostExecute(UDP_Discover.java:57)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
07-29 14:47:46.591 3382-3382/de.liquidbeam.LED.control I/Process﹕ Sending signal. PID: 3382 SIG: 9
Lines:
56 : SharedPreferences settings = getActivity().getSharedPreferences("Found_Devices", 0);
94 : cList.createList();
57: async_cient = new AsyncTask<Void, Void, Void>() {
You creating a new instance of your fragment with no context (activity) to run in. So
the line
SharedPreferences settings = getActivity().getSharedPreferences("Found_Devices", 0);
Tries to get his activity but there is no activity where the fragment lives in ;)
I have a TO DO List, and when I check the checkbox in one Activity I want the CheckBox and the text that is next to the Checkbox to go to another Activity. this is my Adapter:
public class MyItemAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public MyItemAdapter(Context context, String[] values) {
super(context, R.layout.item_list, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.item_list, parent, false);
CheckBox textView = (CheckBox) rowView.findViewById(R.id.checkBox1);
textView.setText(values[position]);
return rowView;
}
public static SparseBooleanArray getCheckedItemPositions() {
// TODO Auto-generated method stub
return null;
}
public static void remove(Object pos) {
// TODO Auto-generated method stub
}
public void changeData(String[] items) {
// TODO Auto-generated method stub
}
public static void setAdapter(MyItemAdapter mAdapter) {
// TODO Auto-generated method stub
}
This is my First Activity code:
final CheckBox check = (CheckBox) findViewById(R.id.checkBox1);
check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, FinishedItems.class);
intent.putExtra("check", items);
Bundle extras = new Bundle();
extras.putString("status", "Data Recived");
intent.putExtras(extras);
startActivity(intent);
}
});
}
This is my Second Activity code:
Intent intent = getIntent();
String check = intent.getStringExtra("check");
((CheckBox)findViewById(R.id.checkBox1)).setText(check);
Bundle bundle = intent.getExtras();
String status = bundle.getString("status");
Toast toast = Toast.makeText(this, status, Toast.LENGTH_LONG);
toast.show();
And Finaly this is my Log cat:
02-18 10:33:24.779: D/AndroidRuntime(1575): Shutting down VM
02-18 10:33:24.779: W/dalvikvm(1575): threadid=1: thread exiting with uncaught exception (group=0x40015560)
02-18 10:33:24.789: E/AndroidRuntime(1575): FATAL EXCEPTION: main
02-18 10:33:24.789: E/AndroidRuntime(1575): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.Stanton.quicktodolist/com.Stanton.quicktodolist.MainActivity}: java.lang.NullPointerException
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.os.Handler.dispatchMessage(Handler.java:99)
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.os.Looper.loop(Looper.java:130)
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.app.ActivityThread.main(ActivityThread.java:3683)
02-18 10:33:24.789: E/AndroidRuntime(1575): at java.lang.reflect.Method.invokeNative(Native Method)
02-18 10:33:24.789: E/AndroidRuntime(1575): at java.lang.reflect.Method.invoke(Method.java:507)
02-18 10:33:24.789: E/AndroidRuntime(1575): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-18 10:33:24.789: E/AndroidRuntime(1575): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-18 10:33:24.789: E/AndroidRuntime(1575): at dalvik.system.NativeStart.main(Native Method)
02-18 10:33:24.789: E/AndroidRuntime(1575): Caused by: java.lang.NullPointerException
02-18 10:33:24.789: E/AndroidRuntime(1575): at com.Stanton.quicktodolist.MainActivity.onCreate(MainActivity.java:70)
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-18 10:33:24.789: E/AndroidRuntime(1575): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
02-18 10:33:24.789: E/AndroidRuntime(1575): ... 11 more
Please Help me
This line of your stacktrace
02-18 10:33:24.789: E/AndroidRuntime(1575): at com.Stanton.quicktodolist.MainActivity.onCreate(MainActivity.java:70)
points you to the error. Line 70 in the MainActivity causes a null pointer. It is often helpful to study and understand stacktraces. If you cannot figure it out yourself, show us the onCreate method of the MainActivity.
I believe that you replace the intent extra by the bundle extra just try this code and let me know pelase
final CheckBox check = (CheckBox) findViewById(R.id.checkBox1);
check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, FinishedItems.class);
intent.putExtra("check", items);
//Bundle extras = new Bundle();
// extras.putString("status", "Data Recived");
intent.putExtras("status", "Data Recived");
startActivity(intent);
}
});
}
And the int the second activity
Intent intent = getIntent();
String check = intent.getStringExtra("check");
((CheckBox)findViewById(R.id.checkBox1)).setText(check);
// Bundle bundle = intent.getExtras();
String status = intent.getStringExtra("status");
Toast toast = Toast.makeText(this, status, Toast.LENGTH_LONG);
toast.show();