how to make a sorting letter as alphabets - java

am new to android ,I juz wanna know how to make like when i click button1, then button2 the text view will show 1 2,,, but if I clicked button2 then button1 it will show 2 1
this is my codes but now when I click button1 then button2, or if i clicked button2 then button1 it shows the same,,
plz help me
thanx.
now I did it using the getText & setText its working as I wanted but the condition if its correct or not is not working plz help !! what is wrong with it and is my method correct?
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Full screen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.wordgame2);
bu1 = (Button) findViewById(R.id.bu1);
bu2 = (Button) findViewById(R.id.bu2);
bu3 = (Button) findViewById(R.id.bu3);
bu4 = (Button) findViewById(R.id.bu4);
bu5 = (Button) findViewById(R.id.bu5);
t1 = (TextView) findViewById(R.id.t1);
i1 = (ImageView) findViewById(R.id.i1);
i2 = (ImageView) findViewById(R.id.i2);
bu1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
t1.setText(t1.getText()+" "+bu1.getText());
}
});
bu2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
t1.setText(t1.getText()+" "+bu2.getText());
}
});
bu3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
t1.setText(t1.getText()+" "+bu3.getText());
}
});
bu4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
t1.setText(t1.getText()+" "+bu4.getText());
}
});
bu5.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(t1.getText().toString().equals("a b c d")) //this is not working
{
i1.setVisibility(View.VISIBLE);
i2.setVisibility(View.INVISIBLE);
}
else {
i2.setVisibility(View.VISIBLE);
i1.setVisibility(View.INVISIBLE);
}
}
});
}
04-21 07:00:48.690: E/AndroidRuntime(23874): FATAL EXCEPTION: main
04-21 07:00:48.690: E/AndroidRuntime(23874): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.arabicalphabets.reham/com.arabicalphabets.reham.Wordgame2}: java.lang.NullPointerException
04-21 07:00:48.690: E/AndroidRuntime(23874): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1970)
04-21 07:00:48.690: E/AndroidRuntime(23874): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1995)
04-21 07:00:48.690: E/AndroidRuntime(23874): at android.app.ActivityThread.access$600(ActivityThread.java:127)
04-21 07:00:48.690: E/AndroidRuntime(23874): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1161)
04-21 07:00:48.690: E/AndroidRuntime(23874): at android.os.Handler.dispatchMessage(Handler.java:99)
04-21 07:00:48.690: E/AndroidRuntime(23874): at android.os.Looper.loop(Looper.java:137)
04-21 07:00:48.690: E/AndroidRuntime(23874): at android.app.ActivityThread.main(ActivityThread.java:4512)
04-21 07:00:48.690: E/AndroidRuntime(23874): at java.lang.reflect.Method.invokeNative(Native Method)
04-21 07:00:48.690: E/AndroidRuntime(23874): at java.lang.reflect.Method.invoke(Method.java:511)
04-21 07:00:48.690: E/AndroidRuntime(23874): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:982)
04-21 07:00:48.690: E/AndroidRuntime(23874): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:749)
04-21 07:00:48.690: E/AndroidRuntime(23874): at dalvik.system.NativeStart.main(Native Method)
04-21 07:00:48.690: E/AndroidRuntime(23874): Caused by: java.lang.NullPointerException
04-21 07:00:48.690: E/AndroidRuntime(23874): at com.arabicalphabets.reham.Wordgame2.onCreate(Wordgame2.java:36)
04-21 07:00:48.690: E/AndroidRuntime(23874): at android.app.Activity.performCreate(Activity.java:4465)
04-21 07:00:48.690: E/AndroidRuntime(23874): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1052)
04-21 07:00:48.690: E/AndroidRuntime(23874): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1934)
04-21 07:00:48.690: E/AndroidRuntime(23874): ... 11 more

first instead of declaring each button individually use looping to declare them...
Button[] buttons;
for(int i=0; i<5; i++) { //for your 5 buttons
{
String buttonID = "bu" + (i+1);
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[i] = ((Button) findViewById(resID));
}
-using switch() find the clicked button...
-and as cases implement the onclick() as below
public void onClick(View v) {
t1.setText(t1.getText().toString()+" "+buttons[i].getText().toString());
}
hope it works

I cant see what is wrong with it and why its crashing and why the if else statement isn't working...??
public class Wordgame2 extends Activity implements OnClickListener {
Button[] buttons;
TextView t1;
ImageView i1, i2;
int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Full screen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.wordgame2);
for(int i=0; i<5; i++) {
{
String buttonID = "bu" + (i+1);
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[i] = ((Button) findViewById(resID));
buttons[i].setOnClickListener(this);
}
}
t1 = (TextView) findViewById(R.id.t1);
i1 = (ImageView) findViewById(R.id.i1);
i2 = (ImageView) findViewById(R.id.i2);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()){
case R.id.bu1:
t1.setText(t1.getText().toString()+" "+buttons[i].getText().toString());
break;
case R.id.bu2:
t1.setText(t1.getText().toString()+" "+buttons[i].getText().toString());
break;
case R.id.bu3:
t1.setText(t1.getText().toString()+" "+buttons[i].getText().toString());
break;
case R.id.bu4:
t1.setText(t1.getText().toString()+" "+buttons[i].getText().toString());
break;
//when they click bu5 if t1 is correct as "a b c d" it will show picture
case R.id.bu5:
if(t1.getText().toString().equals("a b c d")) //this is not working
{
i1.setVisibility(View.VISIBLE);
i2.setVisibility(View.INVISIBLE);
}
else {
i2.setVisibility(View.VISIBLE);
i1.setVisibility(View.INVISIBLE);
}
break;
}
}
}

Related

Android NULL Pointer Exception and Fragment data transmission [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am a beginner at android studio, I have a mission to redesign the app. I use the Fragment. But when I run my app, it has stopped and there is no error in my Gradle. I looked for many website to solve my question, but still have no idea.
I have some questions below.
How can I fix the java.lang.RuntimeException (NULL Pointer Exception) ?
09-30 02:59:56.574 17706-17706/? E/memtrack: Couldn't load memtrack module (No such file or directory)
09-30 02:59:56.574 17706-17706/? E/android.os.Debug: failed to load memtrack module: -2
09-30 02:59:56.996 17722-17722/? E/memtrack: Couldn't load memtrack module (No such file or directory)
09-30 02:59:56.996 17722-17722/? E/android.os.Debug: failed to load memtrack module: -2
09-30 02:59:57.090 17734-17734/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: tw.com.flag.parking22, PID: 17734
java.lang.RuntimeException: Unable to start activity ComponentInfo{tw.com.flag.parking22/tw.com.flag.parking22.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at tw.com.flag.parking22.MainActivity.init(MainActivity.java:102)
at tw.com.flag.parking22.MainActivity.onCreate(MainActivity.java:71)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5254) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
09-30 02:59:57.211 1160-1160/? E/EGL_emulation: tid 1160: eglCreateSyncKHR(1865): error 0x3004 (EGL_BAD_ATTRIBUTE)
09-30 03:02:15.409 2159-19872/com.google.android.gms E/Herrevad: [350] RemoteReportsRefreshChimeraService.a: want to send authenticated request, but no Google account on device
09-30 03:02:15.445 1998-2721/com.google.android.gms.persistent E/SQLiteLog: (2067) abort at 31 in [INSERT INTO pending_ops(source,tag,requires_charging,target_package,source_version,required_network_type,flex_time,target_class,runtime,retry_strategy,last_runtime,period,task_type,job_id,user_
09-30 03:02:15.445 1998-2721/com.google.android.gms.persistent E/SQLiteDatabase: Error inserting source=4 tag=NetworkReportService requires_charging=0 target_package=com.google.android.gms source_version=11509000 required_network_type=2 flex_time=3600000 target_class=com.google.android.gms.common.stats.net.NetworkReportService runtime=1506742923454 retry_strategy={"maximum_backoff_seconds":{"3600":0},"initial_backoff_seconds":{"30":0},"retry_policy":{"0":0}} last_runtime=0 period=7200000 task_type=1 job_id=-1 user_id=0
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: pending_ops.tag, pending_ops.target_class, pending_ops.target_package, pending_ops.user_id (code 2067)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at swi.a(:com.google.android.gms#11509280:208)
at sxo.a(:com.google.android.gms#11509280:64)
at sxp.handleMessage(:com.google.android.gms#11509280:29)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
09-30 03:02:15.446 1998-2721/com.google.android.gms.persistent E/NetworkScheduler: Error persisting task: com.google.android.gms/.common.stats.net.NetworkReportService{u=0 tag="NetworkReportService" trigger=window{period=7200s,flex=3600s,earliest=5988s,latest=9588s} requirements=[NET_ANY] attributes=[PERSISTED,RECURRING] scheduled=2388s last_run=N/A jid=N/A status=PENDING retries=0}
09-30 03:02:15.474 1170-1578/? E/Drm: Failed to find drm plugin
09-30 03:02:15.563 2159-2680/com.google.android.gms E/Volley: [129] BasicNetwork.performRequest: Unexpected response code 307 for https://android.googleapis.com/nova/herrevad/network_quality_info
09-30 03:02:15.888 1998-2721/com.google.android.gms.persistent E/SQLiteLog: (2067) abort at 31 in [INSERT INTO pending_ops(source,tag,requires_charging,target_package,source_version,required_network_type,flex_time,target_class,runtime,retry_strategy,last_runtime,period,task_type,job_id,user_
09-30 03:02:15.888 1998-2721/com.google.android.gms.persistent E/SQLiteDatabase: Error inserting source=4 tag=AggregationTaskTag requires_charging=0 target_package=com.google.android.gms source_version=11509000 required_network_type=2 flex_time=600000 target_class=com.google.android.gms.checkin.EventLogService runtime=1506741123628 retry_strategy={"maximum_backoff_seconds":{"3600":0},"initial_backoff_seconds":{"30":0},"retry_policy":{"0":0}} last_runtime=0 period=1800000 task_type=1 job_id=-1 user_id=0
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: pending_ops.tag, pending_ops.target_class, pending_ops.target_package, pending_ops.user_id (code 2067)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at swi.a(:com.google.android.gms#11509280:208)
at sxo.a(:com.google.android.gms#11509280:64)
at sxp.handleMessage(:com.google.android.gms#11509280:29)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
09-30 03:02:15.888 1998-2721/com.google.android.gms.persistent E/NetworkScheduler: Error persisting task: com.google.android.gms/.checkin.EventLogService{u=0 tag="AggregationTaskTag" trigger=window{period=1800s,flex=600s,earliest=1787s,latest=2387s} requirements=[NET_ANY] attributes=[PERSISTED,RECURRING] scheduled=587s last_run=N/A jid=N/A status=PENDING retries=0}
09-30 03:03:37.417 1170-1578/? E/audio_hw_generic: Error opening input stream format 1, channel_mask 0010, sample_rate 16000
09-30 03:30:15.406 2159-21157/com.google.android.gms E/Herrevad: [355] RemoteReportsRefreshChimeraService.a: want to send authenticated request, but no Google account on device
09-30 03:30:15.511 2159-21162/com.google.android.gms E/ZappConnFactory: Unable to bind to PlayStore
09-30 03:30:15.518 2159-21168/com.google.android.gms E/ZappLogOperation: Unable to bind to Phonesky
09-30 03:30:15.526 2159-21162/com.google.android.gms E/ZappConnFactory: Unable to bind to PlayStore
09-30 03:30:15.526 2159-21162/com.google.android.gms E/ZappConnFactory: Unable to bind to PlayStore
09-30 03:30:15.551 2159-2678/com.google.android.gms E/Volley: [127] BasicNetwork.performRequest: Unexpected response code 307 for https://android.googleapis.com/nova/herrevad/network_quality_info
09-30 03:30:15.572 1170-1578/? E/Drm: Failed to find drm plugin
09-30 03:30:22.524 2159-2159/com.google.android.gms E/ActivityThread: Service com.google.android.gms.chimera.GmsIntentOperationService has leaked ServiceConnection ctn#2f714ea6 that was originally bound here
android.app.ServiceConnectionLeaked: Service com.google.android.gms.chimera.GmsIntentOperationService has leaked ServiceConnection ctn#2f714ea6 that was originally bound here
at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:1077)
at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:971)
at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1774)
at android.app.ContextImpl.bindService(ContextImpl.java:1757)
at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
at com.google.android.gms.chimera.container.zapp.ZappLogOperation.onHandleIntent(:com.google.android.gms#11509280:1)
at com.google.android.chimera.IntentOperation.onHandleIntent(:com.google.android.gms#11509280:2)
at bwy.run(:com.google.android.gms#11509280:10)
at bwv.run(:com.google.android.gms#11509280:14)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
09-30 03:44:15.607 1998-2721/com.google.android.gms.persistent E/SQLiteLog: (2067) abort at 31 in [INSERT INTO pending_ops(source,tag,requires_charging,target_package,source_version,required_network_type,flex_time,target_class,runtime,retry_strategy,last_runtime,period,task_type,job_id,user_
09-30 03:44:15.607 1998-2721/com.google.android.gms.persistent E/SQLiteDatabase: Error inserting source=4 tag=AggregationTaskTag requires_charging=0 target_package=com.google.android.gms source_version=11509000 required_network_type=2 flex_time=600000 target_class=com.google.android.gms.checkin.EventLogService runtime=1506743055606 retry_strategy={"maximum_backoff_seconds":{"3600":0},"initial_backoff_seconds":{"30":0},"retry_policy":{"0":0}} last_runtime=0 period=1800000 task_type=1 job_id=-1 user_id=0
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: pending_ops.tag, pending_ops.target_class, pending_ops.target_package, pending_ops.user_id (code 2067)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at swi.a(:com.google.android.gms#11509280:208)
at sxo.a(:com.google.android.gms#11509280:64)
at sxp.handleMessage(:com.google.android.gms#11509280:29)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
09-30 03:44:15.607 1998-2721/com.google.android.gms.persistent E/NetworkScheduler: Error persisting task: com.google.android.gms/.checkin.EventLogService{u=0 tag="AggregationTaskTag" trigger=window{period=1800s,flex=600s,earliest=1199s,latest=1799s} requirements=[NET_ANY] attributes=[PERSISTED,RECURRING] scheduled=0s last_run=N/A jid=N/A status=PENDING retries=0}
09-30 03:44:15.637 2159-21184/com.google.android.gms E/Herrevad: [371] RemoteReportsRefreshChimeraService.a: want to send authenticated request, but no Google account on device
09-30 03:44:15.755 2159-2676/com.google.android.gms E/Volley: [126] BasicNetwork.performRequest: Unexpected response code 307 for https://android.googleapis.com/nova/herrevad/network_quality_info
09-30 03:46:13.425 1171-1171/? E/installd: eof
09-30 03:46:13.425 1171-1171/? E/installd: failed to read size
Here is the main activity code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager =(ViewPager) findViewById(R.id.pager);
PagerAdapter padapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(padapter);
//--------------------------------------------------------------------
init();
Action();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
}
else {
}
}
private void init(){
System.out.println("start---------------------");
textView_userIDVal = (TextView) findViewById(R.id.textView_userIDVal);
textView_parkingNoVal = (TextView) findViewById(R.id.textView_parkingNoVal);
textView_pillarNoVal = (TextView) findViewById(R.id.textView_pillarNoVal);
textView_colorVal = (TextView) findViewById(R.id.textView_colorVal);
imageView = (ImageView) findViewById(R.id.imageView);
button_space = (Button) findViewById(R.id.button_space);
button_scan = (Button) findViewById(R.id.button_scan);
button_find = (Button) findViewById(R.id.button_find);
simpleDateFormat = new SimpleDateFormat("MM/dd 'at' HH");
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
userID = Build.SERIAL;
//-------------error start next----------------
textView_userIDVal.setText("User ID : " + userID);
}
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CAMERA}, 200);
}
sharedPreferences = getSharedPreferences("Data", 0);
if(sharedPreferences.contains("parkingNum") && sharedPreferences.contains("time")) {
parkingNumtmp = sharedPreferences.getString("parkingNum", "");
textView_parkingNoVal.setText("Parking No. : " + parkingNumtmp + "\t(" + sharedPreferences.getString("time", "") + ")");
}
builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder_timeout = new AlertDialog.Builder(this);
builder_timeout.setTitle("REMIND");
builder_timeout.setMessage("Do you find your car ?");
builder_timeout.setCancelable(false);
builder_timeout.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try {
json_data = new JSONObject();
json_data.put("MT", "timeout");
json_data.put("PlaceMac", parkingNumtmp);
json_data.put("UserMac", userID);
json_write = new JSONObject();
json_write.put("Data", json_data);
json_write.put("Read", false);
isCloseScreen = false;
} catch (JSONException e) {
e.printStackTrace();
}
thread = new Thread(TCP);
thread.start();
timer_count = 0;
startFlag = false;
}
});
builder_timeout.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
maxTime = 10;
maxTime = maxTime / 2;
timer_count = 0;
startFlag = true;
}
});
}
private void Action(){
button_space.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
json_data = new JSONObject();
json_data.put("MT", "count");
json_write = new JSONObject();
json_write.put("Data", json_data);
json_write.put("Read", true);
//System.out.println(json_write + "\n");
} catch (JSONException e) {
e.printStackTrace();
}
thread = new Thread(TCP);
thread.start();
/*builder.setTitle("INFORMATION");
builder.setMessage("All : " + "\nNow : " );
AlertDialog alertDialog = builder.create();
alertDialog.show();*/
}
});
button_scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ScanActivity.class);
startActivityForResult(intent, REQUEST_CODE);
}
});
button_find.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(parkingNumtmp != null) {
try {
maxTime = 10;
json_data = new JSONObject();
json_data.put("MT", "search");
json_data.put("PlaceMac", parkingNumtmp);
json_data.put("UserMac", userID);
json_write = new JSONObject();
json_write.put("Data", json_data);
json_write.put("Read", true);
//System.out.println(json_write + "\n");
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Don't close the screen before you find your car ! ", Toast.LENGTH_LONG).show();
thread = new Thread(TCP);
thread.start();
}
else {
builder.setTitle("WARNING");
builder.setMessage("Please scan QRcode first!");
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
if(data != null) {
final Barcode barcode = data.getParcelableExtra("barcode");
parkingNumtmp = barcode.displayValue;
Date date = new Date();
final String time = simpleDateFormat.format(date);
sharedPreferences.edit().putString("parkingNum", parkingNumtmp).putString("time", time).commit();
textView_parkingNoVal.post(new Runnable() {
#Override
public void run() {
textView_parkingNoVal.setText("Parking No. : " + parkingNumtmp + "\t(" + time +")");
}
});
}
}
}
About Fragment. Is there any setting I have to do when I receive data form sever?
I want to put the received data to TextView in the another view .
Your init() function is probably try to find views inside fragments in view pager. However, at that moment, the fragments are not inflated yet, so your views in the activity are null and trying to do operation on them gives NPE. You should use onCreateView() of Fragment classes to find those views. Then you may notify main activity via callback mechanism.
For example, create FirstFragment as follows:
public class FirstFragment extends Fragment {
private OnFirstFragmentReadyListener callback;
#Override
public void onAttach(Context context) {
super.onAttach(context);
// This makes sure that the container activity has implemented the callback.
try {
callback = (OnFirstFragmentReadyListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement OnFirstFragmentReadyListener");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_first, container, false);
return rootView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Notify the parent activity that the fragment is inflated.
callback.onFirstFragmentReady();
}
public interface OnFirstFragmentReadyListener {
void onFirstFragmentReady();
}
}
Let the layout of FirstFragment as follows (referenced above as fragment_first):
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/first_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Assume we created two more similar fragment classes named as SecondFragment and ThirdFragment. Then the activity should be like this:
public class MainActivity extends AppCompatActivity implements FirstFragment.OnFirstFragmentReadyListener,
SecondFragment.OnSecondFragmentReadyListener, ThirdFragment.OnThirdFragmentReadyListener {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager =(ViewPager) findViewById(R.id.pager);
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
// Don't call these functions here, spread them into callbacks.
// init();
// Action();
}
#Override
public void onFirstFragmentReady() {
TextView firstTextView = (TextView) findViewById(R.id.first_label);
...
// Now you have the views from FirstFragment instance.
// You can now call setText() or setOnClickListener() here.
}
#Override
public void onSecondFragmentReady() {
TextView secondTextView = (TextView) findViewById(R.id.second_label);
...
// Now you have the views from SecondFragment instance.
// You can now call setText() or setOnClickListener() here.
}
#Override
public void onThirdFragmentReady() {
TextView thirdTextView = (TextView) findViewById(R.id.third_label);
...
// Now you have the views from ThirdFragment instance.
// You can now call setText() or setOnClickListener() here.
}
}
Although this code works, this may not be the best way. I think it is better to do operations on views like setting texts or assigning OnClickListeners in fragments itself. If you need to notify a fragment after an action happened in the parent activity, you can implement public methods inside fragments and you can call them from the parent activity when needed.
In fragment you should call the function in onCreateView function(reason as mention by #Mehmed) which is something like below:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.your_fragment, container, false);
//all findViewById;
TextView yourTextView = (Text)view.findViewById(R.id.yourTextView);
//here call for your function
init();
// any other function goes here
return view;
}

Error using Intent when moving to another Activity [duplicate]

This question already has answers here:
Android - Activity Not Found Exception
(13 answers)
Closed 7 years ago.
So I want to move to a new class using an Intent (from ClassicMode class to Person class) in the check() function. I create a new class but when I get to the startActivity(intent) line I get an error but I can't figure out why.
I used Log.d to try and find the problem with no luck. I hope you can help me. I will put stack trace below, thank you.
ClassicMode.java
public class ClassicMode extends Activity implements AnimationListener{//מהמשחק עצמו
String pic;//תמונה של הדגל
Button answer1;//תשובות
Button answer2;
Button answer3;
Button answer4;
Button hint;
TextView guess;
TextView numOfGuess;
TextView score;
TextView scorenum;
MediaPlayer mpHint;
MediaPlayer mpNext;
MediaPlayer mpWrong;
Animation animationfadein;
Animation animationfadeout;
String fn;
Guesses G;
Score s;
Button [] b = new Button[4];
DatabaseHandler db = new DatabaseHandler(this);
List<String>WrongAnswers=new ArrayList<String>();
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
score =(TextView)findViewById(R.id.score);
scorenum =(TextView)findViewById(R.id.scorenum);
scorenum.setText(String.valueOf(s.score));
guess =(TextView)findViewById(R.id.guesses);
numOfGuess=(TextView)findViewById(R.id.numOfGuesses);
numOfGuess.setText(String.valueOf(Guesses.numOfGuesses));
hint =(Button)findViewById(R.id.hint);
hint.setOnClickListener(hintOnClickListener);
mpHint = MediaPlayer.create(this,R.raw.hint_sound);
mpNext = MediaPlayer.create(this, R.raw.next_flag);
mpWrong = MediaPlayer.create(this, R.raw.wrong_answer);
animationfadein = AnimationUtils.loadAnimation(this, R.anim.fade_in);
animationfadeout = AnimationUtils.loadAnimation(this, R.anim.fade_out);
Flags f = new Flags();
Random r = new Random();//הדגל שיבחר לשאלה
int num = r.nextInt(160);//Up
f = db.getFlag(num);//הצגת הדגל הרנדומלי שיצא
fn = f.getName().toString();
pic = f.getImage().toString();
pic_view(pic);//מעבר לפונקציה להשמת התמונה של הדגל במשחק
//מערך ארבע כפתורים כנגד ארבע תשובות
b[0] = (Button)findViewById(R.id.button1);
b[1] = (Button)findViewById(R.id.button2);
b[2] = (Button)findViewById(R.id.button3);
b[3] = (Button)findViewById(R.id.button4);
List<String>Answers=new ArrayList<String>();//מערך תשובות
Answers.add(f.getName().toString());//הוספת התשובה הנכונה
for(int i=1;i<4;i++)
{
num = r.nextInt(200);
String valToAdd1 = db.getFlag(num).getName().toString();
if(!Answers.contains(valToAdd1)){
WrongAnswers.add(valToAdd1);
Answers.add(valToAdd1);
}
}
/*num = r.nextInt(30);
Answers.add(db.getFlag(num).getName().toString());//הוספת 3 תשובות רנדומליות
num = r.nextInt(30);
Answers.add(db.getFlag(num).getName().toString());
num = r.nextInt(30);
Answers.add(db.getFlag(num).getName().toString());*/
Collections.shuffle(Answers);//ערבוב התשובות
for(int i=0;i<Answers.size();i++)
{
b[i].setText(Answers.get(i));//השמת התשובות מהמהערך למערך הכפתורים
b[i].startAnimation(animationfadein);
}
}//end of OnCreat
public boolean onOptionsItemSelected(MenuItem item){//actionbar activity
Intent myIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivityForResult(myIntent, 0);
return true;
}
#SuppressLint("NewApi")
public void resetQuiz()
{
recreate();
}
private OnClickListener hintOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mpHint.start();
if(Guesses.numOfGuesses==1)
{
G.setNumOfGuesses(3);
finish();//כאשר מספר הניחושים
return;
}
else
G.numOfGuesses--;
int invisblecount=0;
for(int i=0;i<b.length;i++){
if(invisblecount<2){
String buttonText = b[i].getText().toString();
if(buttonText.equals(WrongAnswers.get(0))||buttonText.equals(WrongAnswers.get(1)))
{
b[i].startAnimation(animationfadeout);
b[i].setVisibility(View.INVISIBLE);
invisblecount++;
}
}
}
}
};
public void check(View v)
{
Log.d("yes", fn);
Button b = (Button)v;
String text = b.getText().toString();
if(text.equals(fn))
{
mpNext.start();
s.score+=5;
resetQuiz();
}
else
{
mpWrong.start();
if(Guesses.numOfGuesses==1)
{
Log.d("kkk", "inside if");
G.setNumOfGuesses(3);
//finish();//כאשר מספר הניחושים
Intent person = new Intent(ClassicMode.this,Person.class);
String extra = scorenum.getText().toString();
Log.d("lll", "Get Extra");
person.putExtra("Score", extra);
Log.d("sss", "new activ");
startActivity(person);
Log.d("dasdas", "inside Activ");
Toast toast = Toast.makeText(getApplicationContext(), "No more guesses :( Lets see what you made so far...", Toast.LENGTH_SHORT);
toast.show();
/*Intent person = new Intent(ClassicMode.this,Person.class);
String extra = scorenum.getText().toString();
person.putExtra("Score",extra);
startActivity(person);
Log.d("kkk", "inside person");*/
//return;
}
Guesses.numOfGuesses--;
if(s.score>0)
s.score-=5;
scorenum.setText(String.valueOf(s.score));
numOfGuess.setText(String.valueOf(Guesses.numOfGuesses));
}
}
#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;
}
private void pic_view(String pic2) {
// TODO Auto-generated method stub
//גישה לדגל לפי שמו וייבוא התמונה
Log.d("Result from pic function " , pic2);
ImageView imageView = (ImageView)findViewById(R.id.imageView1);
String uri ="#drawable/";
uri += pic2;
int imageResource = getResources().getIdentifier(uri, pic2, getPackageName());//הצוות התמונה
Drawable res= getResources().getDrawable(imageResource);//ציור התמונה
imageView.setImageDrawable(res);
}
#Override
public void onAnimationEnd(Animation animation) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "Animatoin Stoped", Toast.LENGTH_SHORT).show();
}
#Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
}
Person.java
public class Person extends Activity{
EditText name;
Button ok;
TextView enter;
String score;
Map<String,String>Names=new HashMap<String,String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_person);
Intent intent = getIntent();
score = intent.getStringExtra(score);
name =(EditText)findViewById(R.id.namep);
ok =(Button)findViewById(R.id.send);
enter =(TextView)findViewById(R.id.entername);
ok.setOnClickListener(SendActionListener);
}
private OnClickListener SendActionListener = new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Names.put(name.getText().toString(),score);
}
};
}
stacktrace:
04-17 17:45:46.030: D/kkk(5537): inside if
04-17 17:45:46.030: D/lll(5537): Get Extra
04-17 17:45:46.030: D/sss(5537): new activ
04-17 17:45:46.030: I/Timeline(5537): Timeline: Activity_launch_request id:com.example.flagsgame time:93135823
04-17 17:45:46.030: D/AndroidRuntime(5537): Shutting down VM
04-17 17:45:46.030: W/dalvikvm(5537): threadid=1: thread exiting with uncaught exception (group=0x4162cdb8)
04-17 17:45:46.050: E/AndroidRuntime(5537): FATAL EXCEPTION: main
04-17 17:45:46.050: E/AndroidRuntime(5537): Process: com.example.flagsgame, PID: 5537
04-17 17:45:46.050: E/AndroidRuntime(5537): java.lang.IllegalStateException: Could not execute method of the activity
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.view.View$1.onClick(View.java:3830)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.view.View.performClick(View.java:4445)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.view.View$PerformClick.run(View.java:18446)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.os.Handler.handleCallback(Handler.java:733)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.os.Handler.dispatchMessage(Handler.java:95)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.os.Looper.loop(Looper.java:136)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.app.ActivityThread.main(ActivityThread.java:5146)
04-17 17:45:46.050: E/AndroidRuntime(5537): at java.lang.reflect.Method.invokeNative(Native Method)
04-17 17:45:46.050: E/AndroidRuntime(5537): at java.lang.reflect.Method.invoke(Method.java:515)
04-17 17:45:46.050: E/AndroidRuntime(5537): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
04-17 17:45:46.050: E/AndroidRuntime(5537): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
04-17 17:45:46.050: E/AndroidRuntime(5537): at dalvik.system.NativeStart.main(Native Method)
04-17 17:45:46.050: E/AndroidRuntime(5537): Caused by: java.lang.reflect.InvocationTargetException
04-17 17:45:46.050: E/AndroidRuntime(5537): at java.lang.reflect.Method.invokeNative(Native Method)
04-17 17:45:46.050: E/AndroidRuntime(5537): at java.lang.reflect.Method.invoke(Method.java:515)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.view.View$1.onClick(View.java:3825)
04-17 17:45:46.050: E/AndroidRuntime(5537): ... 11 more
04-17 17:45:46.050: E/AndroidRuntime(5537): Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.flagsgame/com.example.flagsgame.Person}; have you declared this activity in your AndroidManifest.xml?
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1628)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1424)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.app.Activity.startActivityForResult(Activity.java:3424)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.app.Activity.startActivityForResult(Activity.java:3385)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.app.Activity.startActivity(Activity.java:3627)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.app.Activity.startActivity(Activity.java:3595)
04-17 17:45:46.050: E/AndroidRuntime(5537): at com.example.flagsgame.ClassicMode.check(ClassicMode.java:188)
04-17 17:45:46.050: E/AndroidRuntime(5537): ... 14 more
The most likely problem is that the Activity is not declared in AndroidManifest.xml. Your error says:
have you declared this activity in your AndroidManifest.xml?
You should first do that.
From this answer on how to do it:
You put it inside of your application element, like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="your.package.name">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".Activity1" android:label="#string/app_name"></activity>
<activity android:name=".Activity2"></activity>
</application>
<uses-sdk android:minSdkVersion="4" />
</manifest>
Where .Activity2 is your second activity.
Your intent isn't declared in the Manifest file.

Storing and getting values from sharedpreferences in android

I want to store values in sharedpreferences and getting values from sharedpreferences finally display the values in listview. Next I want to remove values from list when click on longpress on specific value .After removing values status updated in sharedpreferences. i done this one but problem is when close application and open again i have to display sharedpreferences vales in listview. but it display NullPointerExeption,
actually my requirement is 1)storing values in sharedpreferences and display values in listview for every click .allowed only five values.And that list values are available in onresume() method also.
2) when long press on specific value of listview it have to remove and and updated values are stored in sharedpreferences also.
my code
public class ListViewDemo1 extends Activity {
/**
* Called when the activity is first created.
*/
Button btn;
static int count;
private ListView list;
public static ArrayList<String> values = new ArrayList<String>();
ArrayList countList = new ArrayList();
private ArrayAdapter adapter;
SharedPreferences shared;
Editor editor;
private static ArrayList<String> sharedList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list = (ListView) findViewById(R.id.list);
btn = (Button) findViewById(R.id.btn);
shared = this.getSharedPreferences("Myprefernces", Context.MODE_WORLD_WRITEABLE);
editor = shared.edit();
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
sharedList = new ArrayList();
count++;
if (count == 1) {
values.add("one");
countList.add(count);
}
if (count == 2) {
values.add("two");
countList.add(count);
}
if (count == 3) {
values.add("three");
countList.add(count);
}
if (count == 4) {
values.add("four");
countList.add(count);
}
if (count == 5) {
values.add("five");
countList.add(count);
}
if (count > 5) {
--count;
Toast.makeText(getApplicationContext(), "" + count, 100).show();
}
//put values to sharedpreferences
editor.putInt("SIZE", values.size());
for (int i = 0; i < values.size(); i++) {
editor.putString("addr" + i, values.get(i));
}
editor.commit();
// getting values from sharedpreference
int size = shared.getInt("SIZE", 0);
for (int k = 0; k < size; k++) {
sharedList.add(shared.getString("addr" + k, ""));
}
adapter = new
ArrayAdapter(ListViewDemo1.this, android.R.layout.simple_list_item_1, sharedList);
list.setAdapter(adapter);
}
});
list.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
--count;
values.remove(arg2);
sharedList.remove(arg2);
editor.clear();
editor.commit();
editor.putInt("SIZE", sharedList.size());
for (int i = 0; i < sharedList.size(); i++) {
editor.putString("addr" + i, sharedList.get(i));
}
editor.commit();
adapter.notifyDataSetChanged();
return true;
}
});
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (sharedList.size() > 0) {
adapter = new
ArrayAdapter(ListViewDemo1.this, android.R.layout.simple_list_item_1, sharedList);
list.setAdapter(adapter);
}
}
}
Logcat
04-21 09:56:02.142: E/AndroidRuntime(1160): FATAL EXCEPTION: main
04-21 09:56:02.142: E/AndroidRuntime(1160): java.lang.RuntimeException: Unable to resume activity {com.views/com.views.ListViewDemo1}: java.lang.NullPointerException
04-21 09:56:02.142: E/AndroidRuntime(1160): at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-21 09:56:02.142: E/AndroidRuntime(1160): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
04-21 09:56:02.142: E/AndroidRuntime(1160): at android.os.Handler.dispatchMessage(Handler.java:99)
04-21 09:56:02.142: E/AndroidRuntime(1160): at android.os.Looper.loop(Looper.java:137)
04-21 09:56:02.142: E/AndroidRuntime(1160): at android.app.ActivityThread.main(ActivityThread.java:5041)
04-21 09:56:02.142: E/AndroidRuntime(1160): at java.lang.reflect.Method.invokeNative(Native Method)
04-21 09:56:02.142: E/AndroidRuntime(1160): at java.lang.reflect.Method.invoke(Method.java:511)
04-21 09:56:02.142: E/AndroidRuntime(1160): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-21 09:56:02.142: E/AndroidRuntime(1160): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-21 09:56:02.142: E/AndroidRuntime(1160): at dalvik.system.NativeStart.main(Native Method)
04-21 09:56:02.142: E/AndroidRuntime(1160): Caused by: java.lang.NullPointerException
04-21 09:56:02.142: E/AndroidRuntime(1160): at com.views.ListViewDemo1.onResume(ListViewDemo1.java:114)
04-21 09:56:02.142: E/AndroidRuntime(1160): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1185)
You instantiate sharedList only in onClick() method of a button. This method is not called when your activity is resumed and sharedList is null.
You need to check if it's not null:
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if(sharedList != null && sharedList.size()>0){
adapter=new ArrayAdapter(ListViewDemo1.this,android.R.layout.simple_list_item_1,sharedList);
list.setAdapter(adapter);
}
}
The problem i think is with initialization(or rather not doing that),
static int count;
public static ArrayList<String> values = new ArrayList<String>();
private static ArrayList<String> sharedList;
Now for eg, not initialized count to a value before:
count++;
if(count==1){
Same needs to be done for sharedList, like new ArrayList...
And yes, the reason being onCreate() is not called before onResume() every time, for more on the refer Android Activity Life Cycle
Check Figure 1. The activity lifecycle. on that link.
It will give you a better idea for your implementation/requirement and how to initialize or work with sharedPref and other components for your activity.
read this I hope help you http://developer.android.com/guide/topics/data/data-storage.html
You can use SharedPreferences:
To save data:
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("text", mSaved.getText().toString());
editor.putInt("selection-start", mSaved.getSelectionStart());
editor.putInt("selection-end", mSaved.getSelectionEnd());
editor.commit();
To retrieve data:
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
int selectionStart = prefs.getInt("selection-start", -1);
int selectionEnd = prefs.getInt("selection-end", -1);

Android using One Spinner with Two Adapters

I have one spinner, two adapters and two buttons
when first button is clicked the maleAdapter is called
when the other button is clicked the femaleAdapter is called.
So far this works perfect.
Now. my problem is when each adapter is called two different arrays are called, obviously, BUT i want them to do different things.
Spinner spinner;
String[] maleItems = { "item 1", "item 2", "item 3" };
String[] femaleItems = { "item 3", "item 2", "item 1", "item 0" };
Button maleButton;
Button femaleButton;
ArrayAdapter<String> maleAdapter;
ArrayAdapter<String> femaleAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ArrayAdapter<String> maleAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, maleItems);
final ArrayAdapter<String> femaleAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, femaleItems);
spinner = (Spinner) findViewById(R.id.spinner1);
spinner.setAdapter(maleAdapter);
spinner.setOnItemSelectedListener(this);
// Buttons
maleButton = (Button) findViewById(R.id.maleButton);
femaleButton = (Button) findViewById(R.id.femaleButton);
maleButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
spinner.setAdapter(maleAdapter);
}
});
femaleButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
spinner.setAdapter(femaleAdapter);
}
});
}
Here on my onItemSelected i want to change what happens depending on which button is pressed.
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
int position = spinner.getSelectedItemPosition();
SpinnerAdapter adap = spinner.getAdapter();
if (adap.equals(maleAdapter)) {
switch (position) {
case 0:
// do something only the maleAdapter does
break;
case 1:
// do something only the maleAdapter does
break;
case 2:
// do something only the maleAdapter does
break;
}
} else if (adap.equals(femaleAdapter)) {
switch (position) {
case 0:
// do something only the femaleAdapter does
break;
case 1:
// do something only the femaleAdapter does
break;
case 2:
// do something only the femaleAdapter does
break;
}
}
}
My onClick method worked perfect but the adapter changing gives me an error and i dont know why.
Error
01-25 04:11:18.873: E/AndroidRuntime(21871): FATAL EXCEPTION: main
01-25 04:11:18.873: E/AndroidRuntime(21871): java.lang.NullPointerException
01-25 04:11:18.873: E/AndroidRuntime(21871): at com.MainActivity.onItemSelected(MainActivity.java:117)
01-25 04:11:18.873: E/AndroidRuntime(21871): at android.widget.AdapterView.fireOnSelected(AdapterView.java:871)
01-25 04:11:18.873: E/AndroidRuntime(21871): at android.widget.AdapterView.access$200(AdapterView.java:42)
01-25 04:11:18.873: E/AndroidRuntime(21871): at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:837)
01-25 04:11:18.873: E/AndroidRuntime(21871): at android.os.Handler.handleCallback(Handler.java:587)
01-25 04:11:18.873: E/AndroidRuntime(21871): at android.os.Handler.dispatchMessage(Handler.java:92)
01-25 04:11:18.873: E/AndroidRuntime(21871): at android.os.Looper.loop(Looper.java:130)
01-25 04:11:18.873: E/AndroidRuntime(21871): at android.app.ActivityThread.main(ActivityThread.java:3691)
01-25 04:11:18.873: E/AndroidRuntime(21871): at java.lang.reflect.Method.invokeNative(Native Method)
01-25 04:11:18.873: E/AndroidRuntime(21871): at java.lang.reflect.Method.invoke(Method.java:507)
01-25 04:11:18.873: E/AndroidRuntime(21871): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912)
01-25 04:11:18.873: E/AndroidRuntime(21871): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:670)
01-25 04:11:18.873: E/AndroidRuntime(21871): at dalvik.system.NativeStart.main(Native Method)
final ArrayAdapter<String> maleAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, maleItems);
it is in the local scope of onCreate remove it and initilaize the global maleAdpter over there
just remove final ArrayAdapter before maleAdapter and femaleAdapter.
I'd recommend keeping two separate OnItemSelectedListeners, one for each adapter. Now, when you swap the adapters, also swap the OnItemSelectedListener. Plain and simple.

How to use Bottom tabActivity in my Activity itself

I want to use bottom tab in my activity,in my old activity itself having some function,without using seperate activity for tab,can i use tab functions in my activity itself,I tried like this.
public class GinfyActivity extends Activity {
/** Called when the activity is first created. */
public GridviewAdapter mAdapter;
private Spinner spinner1;
public String selectprayer;
ArrayList<GridviewAdapter> results = new ArrayList<GridviewAdapter>();
private ArrayList<String> listginfy;
private ArrayList<Integer> listimage;
private GridView gridView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_ginfy);
TabHost mTabHost = (TabHost)findViewById(android.R.id.tabhost);
mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator("TAB 1").setContent(new Intent(GinfyActivity.this,Audioprayer.class)));
mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator("TAB 2").setContent(new Intent(GinfyActivity.this,TTSMeditation.class)));
mTabHost.addTab(mTabHost.newTabSpec("tab_test3").setIndicator("TAB 3").setContent(new Intent(GinfyActivity.this,TTSList.class)));
mTabHost.setCurrentTab(0);
addListenerOnButton();
addListenerOnSpinnerItemSelection();
prepareList();
// prepared arraylist and passed it to the Adapter class
mAdapter = new GridviewAdapter(this,listginfy, listimage);
// Set custom adapter to gridview
gridView = (GridView) findViewById(R.id.gridView1);
gridView.setAdapter(mAdapter);
// Implement On Item click listener
gridView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
if (selectprayer.equals("www.ginfy.com"))
{
switch(position)
{
case 0:
Intent newActivity = new Intent(GinfyActivity.this,MainActivity.class);
startActivity(newActivity);
break;
case 2:
Intent new1Activity = new Intent(GinfyActivity.this,AndroidTabLayoutActivity.class);
startActivity(new1Activity);
break;
default:
Toast.makeText(GinfyActivity.this, "Coming Soon", Toast.LENGTH_LONG).show();
}
}
else
{
switch(position)
{
case 0:
Intent new2Activity = new Intent(GinfyActivity.this,YourPrayerActivity.class);
startActivity(new2Activity);
break;
case 1:
Intent new3Activity = new Intent(GinfyActivity.this,AndroidTabLayoutActivity1.class);
startActivity(new3Activity);
break;
case 3:
Intent new4Activity = new Intent(GinfyActivity.this,ExperiencesActivity.class);
startActivity(new4Activity);
break;
default:
Toast.makeText(GinfyActivity.this, "Coming Soon", Toast.LENGTH_LONG).show();
}
}
}
});
}
public void addListenerOnSpinnerItemSelection() {
{
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
spinner1.setSelection(position);
//spinnerCapital.setSelection(position);
selectprayer = (String) spinner1.getSelectedItem();
//Toast.makeText(getBaseContext(), selectprayer, Toast.LENGTH_SHORT).show();
//String myStatesCapital = (String) spinnerCapital.getSelectedItem();
//tvCapital.setText("My State is " + myState + ".And its Capital is "
//+ myStatesCapital);
}
public void onNothingSelected(AdapterView<?> parent) {
}});
}
}
public void addListenerOnButton() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
}
public void prepareList()
{
listginfy = new ArrayList<String>();
listginfy.add("Prayers");
listginfy.add("Prayer room");
listginfy.add("God gallery");
listginfy.add("Experiences");
listimage = new ArrayList<Integer>();
listimage.add(R.drawable.ginfyprayer);
listimage.add(R.drawable.poojaroom1);
listimage.add(R.drawable.godsgallery);
listimage.add(R.drawable.temp1);
}
}
I declared that tab functions in mylayout also but my activity is not opening,it display my activity has stopped
is showing somelogcat error.
09-12 08:43:45.615: E/AndroidRuntime(2630): FATAL EXCEPTION: main
09-12 08:43:45.615: E/AndroidRuntime(2630): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jsonandroid/com.example.jsonandroid.GinfyActivity}: java.lang.NullPointerException
09-12 08:43:45.615: E/AndroidRuntime(2630): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
09-12 08:43:45.615: E/AndroidRuntime(2630): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
09-12 08:43:45.615: E/AndroidRuntime(2630): at android.app.ActivityThread.access$600(ActivityThread.java:141)
09-12 08:43:45.615: E/AndroidRuntime(2630): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
09-12 08:43:45.615: E/AndroidRuntime(2630): at android.os.Handler.dispatchMessage(Handler.java:99)
09-12 08:43:45.615: E/AndroidRuntime(2630): at android.os.Looper.loop(Looper.java:137)
09-12 08:43:45.615: E/AndroidRuntime(2630): at android.app.ActivityThread.main(ActivityThread.java:5039)
09-12 08:43:45.615: E/AndroidRuntime(2630): at java.lang.reflect.Method.invokeNative(Native Method)
09-12 08:43:45.615: E/AndroidRuntime(2630): at java.lang.reflect.Method.invoke(Method.java:511)
09-12 08:43:45.615: E/AndroidRuntime(2630): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-12 08:43:45.615: E/AndroidRuntime(2630): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-12 08:43:45.615: E/AndroidRuntime(2630): at dalvik.system.NativeStart.main(Native Method)
09-12 08:43:45.615: E/AndroidRuntime(2630): Caused by: java.lang.NullPointerException
09-12 08:43:45.615: E/AndroidRuntime(2630): at com.example.jsonandroid.GinfyActivity.onCreate(GinfyActivity.java:44)
09-12 08:43:45.615: E/AndroidRuntime(2630): at android.app.Activity.performCreate(Activity.java:5104)
09-12 08:43:45.615: E/AndroidRuntime(2630): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
09-12 08:43:45.615: E/AndroidRuntime(2630): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
09-12 08:43:45.615: E/AndroidRuntime(2630): ... 11 more
replace these two lines
public class GinfyActivity extends Activity
TabHost mTabHost = (TabHost)findViewById(android.R.id.tabhost);
with following
public class GinfyActivity extends TabActivity
TabHost mTabHost = getTabHost();
EDIT
change activity which you want to display in following line.
Intent intentAndroid = new Intent().setClass(this, Your_Activity.class);
And if you want only Tab then it's better to use ActionBar as TabHost is deprecated.
Full Example of TabHost
To use ActionBar here is sample code (use Sherlock or appcompat Library for < API 11)
public class MainActivity extends Activity implements TabListener {
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actionBar=getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.addTab(actionBar.newTab().setText("TAB 1").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("TAB 2").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("TAB 3").setTabListener(this));
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
switch (tab.getPosition()) {
case 0:
//start activity here or toast
Toast.makeText(getApplicationContext(), "Start First Activity", Toast.LENGTH_SHORT).show();
break;
case 1:
//start activity here or toast
Toast.makeText(getApplicationContext(), "Start Second Activity", Toast.LENGTH_SHORT).show();
break;
case 2:
//start activity here or toast
Toast.makeText(getApplicationContext(), "Start Third Activity", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
For your your complete requirement https://github.com/AdilSoomro/Iphone-Tab-in-Android

Categories