Error in android.os.Process.killProcess(android.os.Process.myPid()); - java

Ive got an error when i call this android.os.Process.killProcess(android.os.Process.myPid());
My logcat says it is unable to start activity. as my understanding using kill process is to kill task that is running but when i use this it shows that it is starting to call another activity.
here is my code:
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(S_2nd_LoginActivity.this);
alertDialogBuilder.setTitle("Are you sure you want to cancel?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
android.os.Process.killProcess(android.os.Process.myPid());
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
here is my logcat:
03-04 18:28:43.805: E/AndroidRuntime(19417): java.lang.RuntimeException: Unable to start activity ComponentInfo{ph.com.example.Project/ph.com.example.Project.MainActivity}: java.lang.NullPointerException
03-04 18:28:43.805: E/AndroidRuntime(19417): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1815)
03-04 18:28:43.805: E/AndroidRuntime(19417): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1831)
03-04 18:28:43.805: E/AndroidRuntime(19417): at android.app.ActivityThread.access$500(ActivityThread.java:122)
03-04 18:28:43.805: E/AndroidRuntime(19417): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1024)
03-04 18:28:43.805: E/AndroidRuntime(19417): at android.os.Handler.dispatchMessage(Handler.java:99)
03-04 18:28:43.805: E/AndroidRuntime(19417): at android.os.Looper.loop(Looper.java:132)
03-04 18:28:43.805: E/AndroidRuntime(19417): at android.app.ActivityThread.main(ActivityThread.java:4123)
03-04 18:28:43.805: E/AndroidRuntime(19417): at java.lang.reflect.Method.invokeNative(Native Method)
03-04 18:28:43.805: E/AndroidRuntime(19417): at java.lang.reflect.Method.invoke(Method.java:491)
03-04 18:28:43.805: E/AndroidRuntime(19417): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:844)
03-04 18:28:43.805: E/AndroidRuntime(19417): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
03-04 18:28:43.805: E/AndroidRuntime(19417): at dalvik.system.NativeStart.main(Native Method)
03-04 18:28:43.805: E/AndroidRuntime(19417): Caused by: java.lang.NullPointerException
03-04 18:28:43.805: E/AndroidRuntime(19417): at ph.com.example.Project.MainActivity.get_Territory(MainActivity.java:169)
03-04 18:28:43.805: E/AndroidRuntime(19417): at ph.com.example.Project.MainActivity.onCreate(MainActivity.java:74)
03-04 18:28:43.805: E/AndroidRuntime(19417): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1050)
03-04 18:28:43.805: E/AndroidRuntime(19417): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1779)
here is my method of get Territory:
public void get_Territory() {
String territory = String.valueOf(LoginActivity.g_territory);
lbl_user.setText(LoginActivity.txt_username.getText().toString());
String s = l_databaseHandler.get_territoryCode(territory);
String f = l_databaseHandler.get_doctorFname(s);
String l = l_databaseHandler.get_doctorLname(s);
Cursor cursorAllDetails = l_databaseHandler.get_all_sameDoctorname(f, l);
if (cursorAllDetails.getCount() != 0){
fillData(cursorAllDetails);
}else{
save_territory();
}
}
and i call this method this way on my onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l_databaseHandler = new DatabaseHandler(this);
if (l_databaseHandler != null) {
l_databaseHandler.close();
l_databaseHandler.createDB();
}
Constants.from_add = false;
Constants.from_edit = false;
Constants.from_view = false;
cast_views();
get_Territory();
log_out();
}
Any help will be appreciated, thank you. I'd use this before and i use it again the same way, i just dont get it why it is acting this way.

TRy like this
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(S_2nd_LoginActivity.this);
alertDialogBuilder.setTitle("Are you sure you want to cancel?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
And in your onDestroy() method call android.os.Process.killProcess(android.os.Process.myPid());

EditText txt_username;
TextView lbl_user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt_username= (EditText)findViewById(R.id.yourEditTextId);
lbl_user= (TextView )findViewById(R.id.yourTextViewId);
l_databaseHandler = new DatabaseHandler(this);
if (l_databaseHandler != null) {
l_databaseHandler.close();
l_databaseHandler.createDB();
}
Constants.from_add = false;
Constants.from_edit = false;
Constants.from_view = false;
cast_views();
get_Territory();
log_out();
}

try using this.
String name = LoginActivity.txt_username.getText().toString();
if(name != null)
lbl_user.setText(name);
else
lbl_user.setText("");

Related

FatalCrash when I click on a Button

I have this RemoteCar App which has the Buttons,
"LOCK" -> leads you to another Acitivity.
"LOCATION" -> leads you to another Activity.
"START ENGINE" -> Lets you click on it and it changes the txt into
"ENGINE RUNNING".
"REFUEL" -> lets you refuel and increments my ProgressBar(FuelBar).
So the problem I have is that I can't click on START ENGINE or REFUEL anymore since the App keeps crashing for reasons I can not resolve, yet. I can easily click on LOCATION and LOCK those work perfectly fine.
Here I have the ErrorMessage:
05-21 13:39:52.887 1869-1869/? W/gralloc_ranchu: Gralloc pipe failed 05-21 13:39:52.897 1869-1869/? D/OpenGLRenderer: Enabling debug mode 0 05-21 13:39:53.097 1402-1429/system_process I/ActivityManager: Displayed com.example.schwarzerritter.remotecv02/.MainActivity: +546ms 05-21 13:39:53.297 1402-1429/system_process D/gralloc_ranchu: gralloc_unregister_buffer: exiting HostConnection (is buffer-handling thread) 05-21 13:39:56.857 1402-1486/system_process E/ThrottleService: problem during onPollAlarm: java.lang.IllegalStateException: problem parsing stats: java.io.FileNotFoundException: /proc/net/xt_qtaguid/iface_stat_all: open failed: ENOENT (No such file or directory) 05-21 13:42:00.387 1869-1869/? D/AndroidRuntime: Shutting down VM 05-21 13:42:00.387 1869-1869/? W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa6661228) 05-21 13:42:00.387 1869-1869/? E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:4084)
at android.view.View$PerformClick.run(View.java:16966)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4084) 
at android.view.View$PerformClick.run(View.java:16966) 
at android.os.Handler.handleCallback(Handler.java:615) 
at android.os.Handler.dispatchMessage(Handler.java:92) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4745) 
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:786) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
at dalvik.system.NativeStart.main(Native Method) 
Caused by: java.lang.NumberFormatException: Invalid int: "AC : 18"
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parse(Integer.java:375)
at java.lang.Integer.parseInt(Integer.java:366)
at java.lang.Integer.parseInt(Integer.java:332)
at com.example.schwarzerritter.remotecv02.MainActivity.onClick(MainActivity.java:41)
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:4084) 
at android.view.View$PerformClick.run(View.java:16966) 
at android.os.Handler.handleCallback(Handler.java:615) 
at android.os.Handler.dispatchMessage(Handler.java:92) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4745) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511)
MainActivity.Java:
public class MainActivity extends AppCompatActivity {
public ProgressBar fuelBar;
public Button lockButton;
public Button engButton;
public Button refuelButton;
public Button plusButton;
public Button minusButton;
public Button locationButton;
public SeekBar seekBarButton;
public TextView seekText;
int incFuel = 0;
int acNum = 0;
public void onClick(View v) {
engButton = (Button) findViewById(R.id.engB);
refuelButton = (Button) findViewById(R.id.refuelB);
fuelBar = (ProgressBar) findViewById(R.id.fuelProgressBar);
seekBarButton = (SeekBar) findViewById(R.id.seekBar);
seekText = (TextView) findViewById(R.id.seekText);
acNum = Integer.parseInt(seekText.getText().toString());
switch (v.getId()) {
case engB:
if (engButton.getText() == "ENGINE RUNNING") {
engButton.setText("START ENGINE");
} else {
if (fuelBar.getProgress() > 0) {
Toast.makeText(MainActivity.this,"Starting engine..",Toast.LENGTH_SHORT).show();
engButton.setText("ENGINE RUNNING");
if (fuelBar.getProgress() >= 10) {
incFuel = fuelBar.getProgress();
incFuel -= 10;
fuelBar.setProgress(incFuel);
if (fuelBar.getProgress() < 100)
refuelButton.setText("REFUEL");
}
} else
if(fuelBar.getProgress() == 0) {
Toast.makeText(MainActivity.this, "No fuel", Toast.LENGTH_SHORT).show();
engButton.setText("EMPTY GASTANK");
}else
engButton.setText("START ENGINE");
}
break;
case refuelB:
if (fuelBar.getProgress() == 0) {
engButton.setText("START ENGINE");
incFuel = fuelBar.getProgress();
incFuel += 10;
fuelBar.setProgress(incFuel);
} else if (fuelBar.getProgress() < 100) {
incFuel = fuelBar.getProgress();
incFuel += 10;
fuelBar.setProgress(incFuel);
} else {
Toast.makeText(MainActivity.this,"Tank is full",Toast.LENGTH_SHORT).show();
refuelButton.setText("FULL");
}
break;
}
}
public void seek_bar(){
seekBarButton = (SeekBar) findViewById(R.id.seekBar);
seekText = (TextView) findViewById(R.id.seekText);
seekText.setText("AC : " + (seekBarButton.getProgress() + 18));
seekText.setText("AC : " + (seekBarButton.getProgress() + 18));
seekBarButton.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressNum;
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressNum = progress;
seekText.setText("AC : " + (seekBarButton.getProgress() + 18) + "°");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
seekText.setText("AC : " + (seekBarButton.getProgress() + 18) + "°");
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
seekText.setText("AC : " + (seekBarButton.getProgress() + 18) + "°");
}
});
}
public void lockPage() {
lockButton = (Button) findViewById(R.id.lockB);
lockButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent lockPage = new Intent(MainActivity.this, lockDoor.class);
startActivity(lockPage);
}
});
}
public void locationPage() {
locationButton = (Button) findViewById(R.id.locationB);
locationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent locationPage = new Intent(MainActivity.this, location.class);
startActivity(locationPage);
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationButton = (Button) findViewById(R.id.locationB);
lockButton = (Button) findViewById(R.id.lockB);
engButton = (Button) findViewById(R.id.engB);
refuelButton = (Button) findViewById(R.id.refuelB);
fuelBar = (ProgressBar) findViewById(R.id.fuelProgressBar);
fuelBar.setMax(100);
fuelBar.setProgress(30);
refuelButton.setText(R.string.refuelB);
lockButton.setText(R.string.lockB);
locationButton.setText(R.string.locationB);
engButton.setText(R.string.engB);
seekBarButton = (SeekBar) findViewById(R.id.seekBar);
seekText = (TextView) findViewById(R.id.seekText);
int acNum;
seek_bar();
lockPage();
locationPage();
}
}
java.lang.NumberFormatException: Invalid int: "AC : 18"
at com.example.schwarzerritter.remotecv02.MainActivity.onClick(MainActivity.java:41)
You are trying to convert the string AC : 18 to an integer in MainActivity.java line 41.
(Reading error messages helps)

System services not available to activities before onCreate() on trying to implement getSystemService()

So I'm trying to implement a AlertDialog which should open up on pressing the the 'activate' button, but on pressing the button, the app crashes.
Here's my code.
MainActivity-
public class MainActivity extends Activity {
Button activateButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activateButton = (Button)findViewById(R.id.activate);
activateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Speed s = new Speed();
}
});
}
And here's another class called Speed which contains the code for AlertDialog
public class Speed extends Activity {
LocationManager mManager;
final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE );
AlertDialog.Builder box = new AlertDialog.Builder(this);
Speed(){
Status();
}
private void Status(){
if(!mManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
DialogBox();
}
}
protected void DialogBox(){
AlertDialog.Builder box = new AlertDialog.Builder(this);
box.setTitle("The GPS needs to be enabled. Would you like to enable the GPS?").setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
}).setNegativeButton("No", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
final AlertDialog alert = box.create();
alert.show();
}
}
Also, here's the log with error in the context
10-01 21:27:00.439: E/AndroidRuntime(5503): FATAL EXCEPTION: main
10-01 21:27:00.439: E/AndroidRuntime(5503): java.lang.IllegalStateException: System services not available to Activities before onCreate()
10-01 21:27:00.439: E/AndroidRuntime(5503): at android.app.Activity.getSystemService(Activity.java:3989)
10-01 21:27:00.439: E/AndroidRuntime(5503): at com.scimet.admin.driveon.Speed.<init>(Speed.java:12)
10-01 21:27:00.439: E/AndroidRuntime(5503): at com.scimet.admin.driveon.MainActivity$1.onClick(MainActivity.java:25)
10-01 21:27:00.439: E/AndroidRuntime(5503): at android.view.View.performClick(View.java:3534)
10-01 21:27:00.439: E/AndroidRuntime(5503): at android.view.View$PerformClick.run(View.java:14263)
10-01 21:27:00.439: E/AndroidRuntime(5503): at android.os.Handler.handleCallback(Handler.java:605)
10-01 21:27:00.439: E/AndroidRuntime(5503): at android.os.Handler.dispatchMessage(Handler.java:92)
10-01 21:27:00.439: E/AndroidRuntime(5503): at android.os.Looper.loop(Looper.java:137)
10-01 21:27:00.439: E/AndroidRuntime(5503): at android.app.ActivityThread.main(ActivityThread.java:4441)
10-01 21:27:00.439: E/AndroidRuntime(5503): at java.lang.reflect.Method.invokeNative(Native Method)
10-01 21:27:00.439: E/AndroidRuntime(5503): at java.lang.reflect.Method.invoke(Method.java:511)
10-01 21:27:00.439: E/AndroidRuntime(5503): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
10-01 21:27:00.439: E/AndroidRuntime(5503): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
10-01 21:27:00.439: E/AndroidRuntime(5503): at dalvik.system.NativeStart.main(Native Method)
This is my first Android project. and on searching for multiple hours to try and resolve this issue, I've ended up with no solution. Please point out the mistake.
Thank you!
You should put this code inside onCreate method, because it will run when the activity is created.
For example
in your class remove constructor.
Then on onCreate method of the activity you do:
public class MainActivity extends Activity {
LocationManager manager;
AlertDialog.Builder box;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
box = new AlertDialog.Builder(this);
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE );
Status();
}
}
An activity should be used for presenting a different user flow and shouldn't be instantiated using 'new'.
If you replace the Speed instantiation line in MainActivity with this:
Speed s = new Speed(MainActivity.this);
and instead treat Speed as a standard class and pass in the MainActivity as a Context object.
public class Speed{
LocationManager mManager;
final LocationManager manager;
AlertDialog.Builder box;
final Context context;
Speed(Context context){
this.context = context;
mManager = context.getSystemService(Context.LOCATION_SERVICE );
Status();
}
private void Status(){
if(!mManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
DialogBox();
}
}
protected void DialogBox(){
AlertDialog.Builder box = new AlertDialog.Builder(this.context);
box.setTitle("The GPS needs to be enabled. Would you like to enable the GPS?").setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
}).setNegativeButton("No", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
final AlertDialog alert = box.create();
alert.show();
}
}
You will only need to do this if you want to keep the separation between the Speed handling stuff and the activity itself.

public static hashmap clear and put not work properly [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
At first I click the “mn_column” button, then works properly. But I go back and click again “mn_column” or “mn_blog” then it show flowing error :
08-10 02:30:16.441: E/AndroidRuntime(1098): FATAL EXCEPTION: main
08-10 02:30:16.441: E/AndroidRuntime(1098): Process: com.sams.main.news, PID: 1098
08-10 02:30:16.441: E/AndroidRuntime(1098): java.lang.NullPointerException
08-10 02:30:16.441: E/AndroidRuntime(1098): at com.sams.main.news.MainNewsActivity$6.onClick(MainNewsActivity.java:539)
08-10 02:30:16.441: E/AndroidRuntime(1098): at android.view.View.performClick(View.java:4438)
08-10 02:30:16.441: E/AndroidRuntime(1098): at android.view.View$PerformClick.run(View.java:18422)
08-10 02:30:16.441: E/AndroidRuntime(1098): at android.os.Handler.handleCallback(Handler.java:733)
08-10 02:30:16.441: E/AndroidRuntime(1098): at android.os.Handler.dispatchMessage(Handler.java:95)
08-10 02:30:16.441: E/AndroidRuntime(1098): at android.os.Looper.loop(Looper.java:136)
08-10 02:30:16.441: E/AndroidRuntime(1098): at android.app.ActivityThread.main(ActivityThread.java:5017)
08-10 02:30:16.441: E/AndroidRuntime(1098): at java.lang.reflect.Method.invokeNative(Native Method)
08-10 02:30:16.441: E/AndroidRuntime(1098): at java.lang.reflect.Method.invoke(Method.java:515)
08-10 02:30:16.441: E/AndroidRuntime(1098): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-10 02:30:16.441: E/AndroidRuntime(1098): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-10 02:30:16.441: E/AndroidRuntime(1098): at dalvik.system.NativeStart.main(Native Method)
Picture:
Code:
MainNewsActivity.java
public class MainNewsActivity extends TabActivity {
String menuLink;
int menuKey;
private List<RssItem> menuItems = new ArrayList<RssItem>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
Button mnColumn = (Button) layout.findViewById(R.id.mn_column);
mnColumn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
menuKey = 0;
//Varialbes.menuNewsMap.clear();
menuLink = "http://www.aaa.org/rss/rssblog";
menuItems = pareser.getNewsList(menuLink);
Varialbes.menuNewsMap.put(menuKey, menuItems);
Intent intent = new Intent(MainNewsActivity.this,MenuNewsActivity.class);
intent.putExtra(Varialbes.PAPER, paper);
intent.putExtra(Varialbes.MENU_TITLE, "Column");
intent.putExtra(Varialbes.MENU_KEY, menuKey);
startActivity(intent);
}
});
Button mnBlog = (Button) layout.findViewById(R.id.mn_blog);
mnBlog.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
menuKey = 1;
menuLink = "http://www.bbb.org/rss/rssblog";
menuItems = pareser.getNewsList(menuLink);
Varialbes.menuNewsMap.put(menuKey, menuItems);
Intent intent = new Intent(MainNewsActivity.this,MenuNewsActivity.class);
intent.putExtra(Varialbes.PAPER, paper);
intent.putExtra(Varialbes.MENU_TITLE, "Blog");
intent.putExtra(Varialbes.MENU_KEY, menuKey);
startActivity(intent);
}
});
}
}
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/popup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#DEE4DF"
android:orientation="vertical" >
<Button
android:id="#+id/mn_column"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2.98"
android:background="#drawable/menu_selector"
android:gravity="left|center_vertical|center_horizontal"
android:text="Column" />
<Button
android:id="#+id/mn_blog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2.98"
android:background="#drawable/menu_selector"
android:gravity="left|center_vertical|center_horizontal"
android:text="Blog" />
</LinearLayout>
Varialbes.java
public class Varialbes {
public static final String PAPER = "paper";
public static final String MENU_TITLE = "title";
public static final String MENU_KEY = "menu_key";
public static HashMap<Integer, List<RssItem>> menuNewsMap = new HashMap<Integer, List<RssItem>>();
}
MenuNewsActivity.java
public class MenuNewsActivity extends Activity {
private ListView listNews;
private List<RssItem> items;
private Button backButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu_news);
// ..........................Back..........................
backButton = (Button) findViewById(R.id.back_button);
backButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent backIntent = new Intent(MenuNewsActivity.this,
MainNewsActivity.class);
finish();
startActivity(backIntent);
}
});
// ................................................
listNews = (ListView) findViewById(R.id.newsList);
Bundle bundle = getIntent().getExtras();
int paper = bundle.getInt(Varialbes.PAPER);
TextView tv = (TextView) findViewById(R.id.hedderText);
String menutitle = bundle.getString(Varialbes.MENU_TITLE);
int menuKey = bundle.getInt(Varialbes.MENU_KEY);
tv.setText(menutitle);
items = Varialbes.menuNewsMap.get(menuKey);
MenuNewsAdater adapter = new MenuNewsAdater(this,
Varialbes.ICONS[paper], items);
listNews.setAdapter(adapter);
}
}
Please help me.
You pareser variable does not properly. So you
add flowing code:
RssParser pareser= new RssParser();
Try this way:
public void onClick(View v) {
menuKey = 0;
Varialbes.menuNewsMap.clear();
menuLink = "http://www.aaa.org/rss/rssblog";
RssParser pareser= new RssParser();
menuItems = pareser.getNewsList(menuLink);
Varialbes.menuNewsMap.put(menuKey, menuItems);
Intent intent = new Intent(MainNewsActivity.this,MenuNewsActivity.class);
intent.putExtra(Varialbes.PAPER, paper);
intent.putExtra(Varialbes.MENU_TITLE, "Column");
intent.putExtra(Varialbes.MENU_KEY, menuKey);
startActivity(intent);
}

android code for nfc writer

hi this is my java file ......i m developing a nfc writer application.....here down is my java code file
package com.example.nfc_tag_writer;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcAdapter.CreateNdefMessageCallback;
import android.nfc.NfcAdapter.OnNdefPushCompleteCallback;
import android.nfc.NfcEvent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;
import java.nio.charset.Charset;
public class SendTextViaNFCActivity extends Activity implements CreateNdefMessageCallback, OnNdefPushCompleteCallback {
private static final int MESSAGE_SENT = 1;
String CURSOR_HERE;
String SAVED_TEXT;
String beamText;
private final Handler mHandler;
NfcAdapter mNfcAdapter;
EditText myText;
class AnonymousClass_1 extends Handler {
final /* synthetic */ SendTextViaNFCActivity this$0;
AnonymousClass_1(SendTextViaNFCActivity r1_SendTextViaNFCActivity) {
super();
this$0 = r1_SendTextViaNFCActivity;
}
public void handleMessage(Message msg) {
switch(msg.what) {
case MESSAGE_SENT:
Toast.makeText(this$0.getApplicationContext(), "Message sent!", MESSAGE_SENT).show();
}
}
}
public SendTextViaNFCActivity() {
super();
SAVED_TEXT = "SAVED_TEXT";
CURSOR_HERE = "###CURSOR_HERE###";
beamText = "";
mHandler = new AnonymousClass_1(this);
}
public NdefRecord createMimeRecord(String mimeType, byte[] payload) {
return new NdefRecord((short) 2, mimeType.getBytes(Charset.forName("US-ASCII")), new byte[0], payload);
}
public NdefMessage createNdefMessage(NfcEvent event) {
NdefRecord[] r2_NdefRecord_A = new NdefRecord[2];
r2_NdefRecord_A[0] = createMimeRecord("application/com.example.android.beam", myText.getText().toString().getBytes());
r2_NdefRecord_A[1] = NdefRecord.createApplicationRecord("diewland.nfc.text");
return new NdefMessage(r2_NdefRecord_A);
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.send_text_via_nfc);
myText = (EditText) findViewById(R.id.my_text);
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (mNfcAdapter == null) {
myText.setText("NFC is not available on this device.");
myText.setEnabled(false);
}
mNfcAdapter.setNdefPushMessageCallback(this, this, new Activity[0]);
mNfcAdapter.setOnNdefPushCompleteCallback(this, this, new Activity[0]);
}
public boolean onCreateOptionsMenu(Menu menu) {
if (mNfcAdapter == null) {
return super.onCreateOptionsMenu(menu);
} else {
getMenuInflater().inflate(R.menu.options, menu);
return true;
}
}
public void onNdefPushComplete(NfcEvent arg0) {
mHandler.obtainMessage(MESSAGE_SENT).sendToTarget();
}
public void onNewIntent(Intent intent) {
setIntent(intent);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menu_settings:
startActivity(new Intent("android.settings.NFCSHARING_SETTINGS"));
return true;
case R.id.menu_reset:
myText.setText("");
return true;
case R.id.menu_share:
if (!"".equals(myText.getText().toString())) {
Intent sendIntent = new Intent();
sendIntent.setAction("android.intent.action.SEND");
sendIntent.putExtra("android.intent.extra.TEXT", myText.getText().toString());
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, "Share via"));
return true;
} else {
return true;
}
}
return super.onOptionsItemSelected(item);
}
protected void onPause() {
super.onPause();
myText.getText().insert(myText.getSelectionStart(), CURSOR_HERE);
Editor editor = getPreferences(0).edit();
editor.putString(SAVED_TEXT, myText.getText().toString());
editor.commit();
}
public void onResume() {
super.onResume();
Intent intent = getIntent();
String type = intent.getType();
if (!"android.intent.action.SEND".equals(intent.getAction()) || type == null) {
if ("android.nfc.action.NDEF_DISCOVERED".equals(getIntent().getAction())) {
processIntent(getIntent());
}
String restoredText = getPreferences(0).getString(SAVED_TEXT, null);
if (restoredText != null) {
myText.setText(restoredText.replaceAll(CURSOR_HERE, beamText));
}
} else if ("text/plain".equals(type)) {
myText.setText(intent.getStringExtra("android.intent.extra.TEXT"));
}
myText.setSelection(myText.getText().length());
}
void processIntent(Intent intent) {
beamText = new String(((NdefMessage) intent.getParcelableArrayExtra("android.nfc.extra.NDEF_MESSAGES")[0]).getRecords()[0].getPayload());
}
}
i m getting followings errorss
03-19 08:09:56.989: V/NFC(767): this device does not have NFC support
03-19 08:09:56.999: D/AndroidRuntime(767): Shutting down VM
03-19 08:09:56.999: W/dalvikvm(767): threadid=1: thread exiting with uncaught exception (group=0x414c4700)
03-19 08:09:57.029: E/AndroidRuntime(767): FATAL EXCEPTION: main
03-19 08:09:57.029: E/AndroidRuntime(767): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.nfc_tag_writer/com.example.nfc_tag_writer.SendTextViaNFCActivity}: java.lang.NullPointerException
03-19 08:09:57.029: E/AndroidRuntime(767): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
03-19 08:09:57.029: E/AndroidRuntime(767): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
03-19 08:09:57.029: E/AndroidRuntime(767): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-19 08:09:57.029: E/AndroidRuntime(767): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
03-19 08:09:57.029: E/AndroidRuntime(767): at android.os.Handler.dispatchMessage(Handler.java:99)
03-19 08:09:57.029: E/AndroidRuntime(767): at android.os.Looper.loop(Looper.java:137)
03-19 08:09:57.029: E/AndroidRuntime(767): at android.app.ActivityThread.main(ActivityThread.java:5103)
03-19 08:09:57.029: E/AndroidRuntime(767): at java.lang.reflect.Method.invokeNative(Native Method)
03-19 08:09:57.029: E/AndroidRuntime(767): at java.lang.reflect.Method.invoke(Method.java:525)
03-19 08:09:57.029: E/AndroidRuntime(767): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
03-19 08:09:57.029: E/AndroidRuntime(767): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-19 08:09:57.029: E/AndroidRuntime(767): at dalvik.system.NativeStart.main(Native Method)
03-19 08:09:57.029: E/AndroidRuntime(767): Caused by: java.lang.NullPointerException
03-19 08:09:57.029: E/AndroidRuntime(767): at com.example.nfc_tag_writer.SendTextViaNFCActivity.onCreate(SendTextViaNFCActivity.java:75)
03-19 08:09:57.029: E/AndroidRuntime(767): at android.app.Activity.performCreate(Activity.java:5133)
03-19 08:09:57.029: E/AndroidRuntime(767): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
03-19 08:09:57.029: E/AndroidRuntime(767): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
03-19 08:09:57.029: E/AndroidRuntime(767): ... 11 more
please can anyone help me
i m getting the my errors in logcat...i m unable to fix them.....the app is unfornatelly stopping r crashing
Your checking that the mNfcAdapter is not null, yet still try to access it afterward even if it is. Try moving these lines
mNfcAdapter.setNdefPushMessageCallback(this, this, new Activity[0]);
mNfcAdapter.setOnNdefPushCompleteCallback(this, this, new Activity[0]);
into an else to the previous if:
if (mNfcAdapter == null) {
myText.setText("NFC is not available on this device.");
myText.setEnabled(false);
} else {
mNfcAdapter.setNdefPushMessageCallback(this, this, new Activity[0]);
mNfcAdapter.setOnNdefPushCompleteCallback(this, this, new Activity[0]);
}

EditText.getText().toString() crashes

In my android application , I have 3 dialogue boxes in which the user puts info into 3 editTexts and it will display the one of the data onto another class/page after it randomly picks which data to choose.
This is my mainClass
public class MainActivity extends Activity {
//Variables are displayed in this area
String choices[] = new String[3];
//EditText editText;
//EditText editText2;
//EditText editText3;
Button mainButton ;
Random rand = new Random();
int finalChoice;
String displayChoice = "";
EditText editText ;
EditText editText2;
EditText editText3;
EditText editText4;
String test;
int count = 3;
//--------------------------- --------------------------------------------------------
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Makes Button
setContentView(R.layout.activity_main);
declareTextBox();
setButton();
String choice1 = editText.getText().toString();
String choice2 = editText2.getText().toString();
String choice3 = editText3.getText().toString();
choices[0] = choice1; //pass from click button to method.
choices[1] = choice2;
choices[2] = choice3;
finalChoice =rand.nextInt(2);
}
public void setButton()
{
final Button mainbutton = (Button) findViewById(R.id.mainButton);
mainbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
test = ((EditText) findViewById(R.id.editText4)).getText().toString();
// count++;
//retChoice();
// loadScreen();
Intent i = new Intent(MainActivity.this, resultScreen.class);
i.putExtra("display" , displayChoice);
Intent intent = new Intent(MainActivity.this,loadingScreen.class);
//start the second Activity
MainActivity.this.startActivity(intent);
}
});
}
public void declareTextBox()
{
editText = (EditText) findViewById(R.id.editText1);
editText2 = (EditText) findViewById(R.id.editText2);
editText3 = (EditText) findViewById(R.id.editText3);
}
public void getString(String finalChoice)
{
finalChoice = displayChoice;
}
public String retChoice()
{
displayChoice = choices[finalChoice];
return displayChoice;
}
public void clearText()
{
editText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
editText.setText(" ");
}
});
editText2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
editText2.setText(" ");
}
});
editText3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
editText3.setText(" ");
}
});
}
public void getText2()
{
}
public void getText()
{
}
#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;
}
}
This is my Display class :
public class resultScreen extends Activity {
MainActivity ma = new MainActivity();
//Method supposedly retrieves the string data from MainActivity Class but somehow displayed null instead.
//Find a way to keep the string variable when transfering from one class to another class.
String finalResult = ma.retChoice();
public void onCreate(Bundle resultScreen){
super.onCreate(resultScreen);
setContentView(R.layout.resultscreen);
//ma.displayChoice.toString();
String str = finalResult;
TextView text = (TextView) findViewById(R.id.textView1);
text.setText(str);
final Button backbutton = (Button) findViewById(R.id.backButton);
backbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
Intent intent = new Intent(resultScreen.this,MainActivity.class);
resultScreen.this.startActivity(intent);
}
});
}
}
And this is my loading screen class right after the main button is clicked
public class loadingScreen extends Activity{
protected void onCreate(Bundle loadingScreen) {
// TODO Auto-generated method stub
super.onCreate(loadingScreen);
setContentView(R.layout.loadingscreen);
//If sound clip 20 sec long we don't want to carryit outside next class
// A timer thread looking for "run" method
Thread timer = new Thread()
{
public void run() {
try {
//this is how many mil sec
sleep(8000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent intent = new Intent(loadingScreen.this, resultScreen.class);
loadingScreen.this.startActivity(intent);
loadingScreen.this.finish();
}
}
};
timer.start();
}
}
My app crashes a few seconds into the loading screen when the program attempts to display the data on the resultScreen.
Here's my logCat
05-17 22:32:54.446: D/AndroidRuntime(1181): Shutting down VM
05-17 22:32:54.446: W/dalvikvm(1181): threadid=1: thread exiting with uncaught exception (group=0x40a70930)
05-17 22:32:54.636: E/AndroidRuntime(1181): FATAL EXCEPTION: main
05-17 22:32:54.636: E/AndroidRuntime(1181): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.choiceprototest/com.example.choiceprototest.resultScreen}: java.lang.NullPointerException
05-17 22:32:54.636: E/AndroidRuntime(1181): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
05-17 22:32:54.636: E/AndroidRuntime(1181): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
05-17 22:32:54.636: E/AndroidRuntime(1181): at android.app.ActivityThread.access$600(ActivityThread.java:141)
05-17 22:32:54.636: E/AndroidRuntime(1181): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
05-17 22:32:54.636: E/AndroidRuntime(1181): at android.os.Handler.dispatchMessage(Handler.java:99)
05-17 22:32:54.636: E/AndroidRuntime(1181): at android.os.Looper.loop(Looper.java:137)
05-17 22:32:54.636: E/AndroidRuntime(1181): at android.app.ActivityThread.main(ActivityThread.java:5039)
05-17 22:32:54.636: E/AndroidRuntime(1181): at java.lang.reflect.Method.invokeNative(Native Method)
05-17 22:32:54.636: E/AndroidRuntime(1181): at java.lang.reflect.Method.invoke(Method.java:511)
05-17 22:32:54.636: E/AndroidRuntime(1181): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-17 22:32:54.636: E/AndroidRuntime(1181): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-17 22:32:54.636: E/AndroidRuntime(1181): at dalvik.system.NativeStart.main(Native Method)
05-17 22:32:54.636: E/AndroidRuntime(1181): Caused by: java.lang.NullPointerException
05-17 22:32:54.636: E/AndroidRuntime(1181): at com.example.choiceprototest.MainActivity.retChoice(MainActivity.java:101)
05-17 22:32:54.636: E/AndroidRuntime(1181): at com.example.choiceprototest.resultScreen.<init>(resultScreen.java:18)
05-17 22:32:54.636: E/AndroidRuntime(1181): at java.lang.Class.newInstanceImpl(Native Method)
05-17 22:32:54.636: E/AndroidRuntime(1181): at java.lang.Class.newInstance(Class.java:1319)
05-17 22:32:54.636: E/AndroidRuntime(1181): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
05-17 22:32:54.636: E/AndroidRuntime(1181): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
05-17 22:32:54.636: E/AndroidRuntime(1181): ... 11 more
05-17 22:33:03.385: I/Process(1181): Sending signal. PID: 1181 SIG: 9
05-17 22:33:05.435: E/Trace(1204): error opening trace file: No such file or directory (2)
Thanks guys.
I believe I see the problem. You are trying to access your Array but it is an instance variable instead of static so it is being killed off when you exit your Activity. You can either put them in a static class and access them that way or pass a String variable through your Intent, depending on what you need.
If you have the value of the String you need when you leave MainActivity then I would probably just pass it through your Intent. If the value depended on something in one of your other Activities then I would consider putting it in a separate class but it doesn't look like that's what you need here
Edit
You are already doing it here, kind of
Intent i = new Intent(MainActivity.this, resultScreen.class);
i.putExtra("display" , displayChoice);
Intent intent = new Intent(MainActivity.this,loadingScreen.class);
But you aren't starting the Activity that would get the String
i.putExtra("display" , displayChoice);
that line would pass a String with key "displpay" and value of displayChoice, although I think that value is an empty String at that point, but you don't start that Activity. I'm lost on how your flow is suppose to work but basically you would do something like this
String displayChoice = "testValue"; // some arbitrary value--whatever you need to send
Intent i = new Intent(MainActivity.this, resultScreen.class); // create the Intent
i.putExtra("display" , displayChoice); // add the extra
startActivity(i); //start the Activity
then to get the value inside resultScreen in onCreate()
Intent recIntent = getIntent(); // get the Intent that started this Activity
String value = recIntent.getStringExtra("display"); // get the value using the key
// value now equals "testValue"
I think your app chash because you have an ANR: "Application Not Responding" because you are running a long procces inside the UIThread. (onCreate() method is form the UIThread)
Use rather as an Asyntack for your sleeping thread or one handler (with messages).
If you need more I can edit your code tomorrow.

Categories

Resources