there is java class extends FragmentActivity, min-sdk is 10
i used ViewPager with FragmentManager to show images in viewpager indicator
some times it shows me error when i want to exit activity
private static ArrayList<PgItem> image_resource;
public static ArrayList<ProjectItem> items = new ArrayList<ProjectItem>();
private static ViewPager v_pager;
private static TitlePageIndicator pagerIndicator;
public static FragmentManager fgmanger;
public static void setSIAdapter(ArrayList<ProjectItem> inputArray , int ex){
switch (ex){
case 0:
Log.i(App.logs.WEBSERVICE, "CertificateAsync >> inputArray.size : " + inputArray.size());
if(!inputArray.isEmpty()) {
items.clear();
items.addAll(inputArray);
image_resource = new ArrayList<PgItem>();
image_resource.clear();
for (int i = 0; i < inputArray.size(); i++) {
String image = ""+inputArray.get(i).getPrjImage();
if(image.trim().length() > 0 && image.replace(""+App.webServiceConfigs.ROOT , "").trim().length() > 0) {
String text = ""+inputArray.get(i).getPrjTitle();
String ext = image.substring(image.lastIndexOf(".") , image.length());
if(!image.toLowerCase().contains("_xl"+ext)){
image = image.replace(ext , "_XL"+ext);
}
PgItem item = new PgItem(image, text);
image_resource.add(item);
Log.i(App.logs.TEST, "image_resource.image_name # " + (image_resource.size()-1) + " : " + image_resource.get(image_resource.size()-1).getImage());
}
}
FragmentAdapter adapter = new FragmentAdapter(fgmanger , image_resource);
if(v_pager != null){
v_pager.setAdapter(adapter); // Error Line
pagerIndicator.setViewPager(v_pager);
pagerIndicator.setTextSize(UIHelpers.textFont-2);
pagerIndicator.setSelectedBold(true);
pagerIndicator.setSelectedColor(Color.parseColor("#595458"));
pagerIndicator.setTextColor(Color.parseColor("#9E9E9E"));
pagerIndicator.setTypeface(Typeface.createFromAsset(App.configs.currentActivity.getAssets(), "yekan.ttf"));
}
//ImagePagerAdapterPg adapter = new ImagePagerAdapterPg(image_resource);
// v_pager.setAdapter(adapter);
}
break;
case -1:
Toast toastProtocol = Toast.makeText(App.configs.context , App.configs.context.getString(R.string.PROTOCOL_EXCEPTION) , Toast.LENGTH_LONG);
toastProtocol.setGravity(Gravity.CENTER, 0, (int) (UIHelpers.width * 0.25));
toastProtocol.show();
if(App.webServiceConfigs.connectionTimeOut <= 18000) {
App.webServiceConfigs.connectionTimeOut += 3000;
}
if(App.webServiceConfigs.socketTimeOut <= 18000) {
App.webServiceConfigs.socketTimeOut += 3000;
}
callWebservice();
break;
case -2:
Toast toastIO = Toast.makeText(App.configs.context , App.configs.context.getString(R.string.IO_EXCEPTION) , Toast.LENGTH_LONG);
toastIO.setGravity(Gravity.CENTER, 0, (int) (UIHelpers.width * 0.25));
toastIO.show();
if(App.webServiceConfigs.connectionTimeOut <= 20000) {
App.webServiceConfigs.connectionTimeOut += 3000;
}
if(App.webServiceConfigs.socketTimeOut <= 20000) {
App.webServiceConfigs.socketTimeOut += 3000;
}
callWebservice();
break;
case -3:
break;
case -4:
break;
}
}
i load images from cache and show to user, then connect to server and update image adapter again.
it shows me error :
05-19 17:56:27.213 9768-9768/com.emaarIt.app.Bernoulli E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalStateException: Activity has been destroyed
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1358)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:595)
at android.support.v4.app.BackStackRecord.commitAllowingStateLoss(BackStackRecord.java:578)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:139)
at android.support.v4.view.ViewPager.setAdapter(ViewPager.java:415)
at com.emaarIt.app.Bernoulli.activities.ProjectGalleryActivity.setSIAdapter(ProjectGalleryActivity.java:225)
at com.emaarIt.app.Bernoulli.webservice.modules.ProjectGalleryAsync.onPostExecute(ProjectGalleryAsync.java:78)
at com.emaarIt.app.Bernoulli.webservice.modules.ProjectGalleryAsync.onPostExecute(ProjectGalleryAsync.java:32)
at android.os.AsyncTask.finish(AsyncTask.java:602)
at android.os.AsyncTask.access$600(AsyncTask.java:156)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4441)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Cause:
The problem here is that after your activity got destroyed, the AsyncTask was still working and when it finishes it's work it will call AsyncTask's OnPostExecute() callback method and you are setting the adapter of the ViewPager which contacts the Activity to add the Fragments to the back stack and that can't happen because your activity got destroyed.
Proposed Solution:
You can hold a reference to your AsyncTask object and cancel it on the Activity's onDestroy() callback.
protected void onDestroy() {
super.onDestroy();
// cancel the task
if(asyncTask != null && asyncTask.getStatus() != AsyncTask.Status.FINISHED) {
asyncTask.cancel(true);
}
}
What AsyncTask.cancel() do?
Calling this method will result in onCancelled(Object) being invoked
on the UI thread after doInBackground(Object[]) returns. Calling this
method guarantees that onPostExecute(Object) is never invoked.
Related
The error appears in RecyclerView Adapter on different versions of android and devices.
Im retrieving information about download progress every second and show percents on item layout.
#Override
public void onBindViewHolder(final ItemViewHolder holder, final int position) {
final Download item = downloads.get(position);
holder.titleTv.setText(downloads.get(position).getTitle());
Cursor cursor = downloadManager.query(
new DownloadManager.Query().setFilterById(item.getDownloadId()));
if (cursor != null && cursor.moveToNext()) {
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_RUNNING
|| status == DownloadManager.STATUS_PENDING)
new Runnable() {
#Override
public void run() {
Cursor c = downloadManager.query(
new DownloadManager.Query()
.setFilterById(item.getDownloadId()));
float percent = 100;
if (c != null) {
if (c.moveToNext()) {
int downloadedBytes = c.getInt(c.getColumnIndex(
DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)
);
int totalBytes = c.getInt(c.getColumnIndex(
DownloadManager.COLUMN_TOTAL_SIZE_BYTES)
);
percent = totalBytes == 0 ? 0 : downloadedBytes / (float) (totalBytes / 100);
holder.percentTv.setText(String.valueOf(Math.round(percent)).concat("%"));
holder.progressLayout.setCurrentProgress(Math.round(percent));
}
c.close();
}
if (percent != 100)
holder.progressHandler.postDelayed(this, 1000);
}
}.run();
else {
if (status == DownloadManager.STATUS_SUCCESSFUL) {
holder.percentTv.setText("100%");
holder.progressLayout.setCurrentProgress(100);
} if (status == DownloadManager.STATUS_FAILED)
holder.percentTv.setText("Failed");
else
holder.progressLayout.setCurrentProgress(100);
if (!Utils.isFileExists(item.getFilepath()))
item.delete();
}
}
}
Here is crash log
Fatal Exception: java.lang.SecurityException: Requesting code from com.android.providers.downloads (with uid 10026) to be run in process my.package (with uid 10134)
at android.app.ActivityThread.getPackageInfo(ActivityThread.java:1877)
at android.app.ActivityThread.getPackageInfo(ActivityThread.java:1853)
at android.app.ContextImpl.createPackageContextAsUser(ContextImpl.java:2231)
at android.app.ContextImpl.createPackageContext(ContextImpl.java:2217)
at android.app.ActivityThread.installProvider(ActivityThread.java:4977)
at android.app.ActivityThread.acquireProvider(ActivityThread.java:4657)
at android.app.ContextImpl$ApplicationContentResolver.acquireUnstableProvider(ContextImpl.java:2494)
at android.content.ContentResolver.acquireUnstableProvider(ContentResolver.java:1110)
at android.content.ContentResolver.query(ContentResolver.java:365)
at android.content.ContentResolver.query(ContentResolver.java:324)
at android.app.DownloadManager$Query.runQuery(DownloadManager.java:1262)
at android.app.DownloadManager.query(DownloadManager.java:1473)
at my.package.adapters.DownloadsAdapter$1.run(DownloadsAdapter.java:71)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5302)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(NativeStart.java)
Can't figure out whats the crash is, and how to reproduce that crash.
Hope to your help stackoverflow community.
I want to make it clear that this question will look very similar to one I asked earlier, but that I'm not asking exactly the same thing.
In my previous question, I got a RuntimeException/IllegalStateException, which told me my Activity got destroyed upon adding a new fragment.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tim.timapp
/com.example.tim.timapp.MainActivity}: java.lang.IllegalStateException:
Activity has been destroyed
In that case, it turned out it had to do with me creating new instances of MainActivityin an invalid way:
MainActivity ma = new MainActivity();
(PSA: Don't do the above, use MainActivity ma = (MainActivity) getActivity(); instead.)
I have now corrected this in my entire project, and am getting almost exactly the same error. Let me be clear: I (think I) know the original error was fixed, because I got a different error in between these two RE's, which I was able to fix myself.
To reiterate on my gibberish: Got the first RE, fixed it with the answer on my question, got a different error, fixed that myself, got almost exactly the same RE.
I have searched through my entire project to see if I had anything similar to the error I made before, but I can't find anything, so here I am. So basically, the answer I got on my previous question fixed my issue, temporarily. That answer however, does not help me with this new error I'm getting, that's why I'm asking this question.
TL;DR: Answer on Q1 fixed my issue at first(which makes it a working answer), but it does not fix the issue I'm having right now, which is almost the same.
The actual question
So, now we've got that bit out of the way, let's get on with my issue. So, I'm getting a RuntimeException/IllegalStateExcetion:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.tim.timapp/com.example.tim.timapp.MainActivity}:
java.lang.IllegalStateException: Activity has been destroyed
(PS. It's only a RE because I have my app navigate to the GeneralSettings fragment on startup, for debugging ease.)
I've read up on this kind of error, but nothing I could find that applies on my project.
So, what is causing this RuntimeException/IllegalStateException?
Full log
04-05 14:17:53.140 23411-23411/? I/art: Not late-enabling -Xcheck:jni (already on)
04-05 14:17:53.190 23411-23411/com.example.tim.timapp W/System: ClassLoader referenced unknown path: /data/app/com.example.tim.timapp-1/lib/x86_64
04-05 14:17:53.210 23411-23411/com.example.tim.timapp D/TEST DBHandler: sInstance == null
04-05 14:17:53.370 23411-23411/com.example.tim.timapp D/AndroidRuntime: Shutting down VM
04-05 14:17:53.370 23411-23411/com.example.tim.timapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.tim.timapp, PID: 23411
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tim.timapp/com.example.tim.timapp.MainActivity}: java.lang.IllegalStateException: Activity has been destroyed
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IllegalStateException: Activity has been destroyed
at android.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1433)
at android.app.BackStackRecord.commitInternal(BackStackRecord.java:687)
at android.app.BackStackRecord.commit(BackStackRecord.java:663)
at com.example.tim.timapp.MainActivity.DrawVariableFragments(MainActivity.java:276)
at com.example.fragments.Settings.GeneralSettingsFragment.onCreateView(GeneralSettingsFragment.java:58)
at android.app.Fragment.performCreateView(Fragment.java:2220)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:973)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1148)
at android.app.BackStackRecord.run(BackStackRecord.java:793)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1535)
at android.app.FragmentController.execPendingActions(FragmentController.java:325)
at android.app.Activity.performStart(Activity.java:6252)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
MainActivity (Snippet)
package com.example.tim.timapp;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static boolean isMainShown = false;
private static boolean isSettingsShown = false;
private static boolean doSavePopup = false;
private static String backTitle = "";
private String tag = "TEST MA";
DBHandler dbHandler;
Menu menu;
public void DrawVariableFragments(String base,String token){
// FragmentManager fm = getFragmentManager();
ArrayList<String> Data;
dbHandler = DBHandler.getInstance(this);
int AmountOfEntries;
int SettingsContainer;
String SettingsTag;
Fragment SettingsVariableFragment;
Fragment SettingsEmptyFragment;
if (base.equalsIgnoreCase("StuffManager")) {
Data = new ArrayList<String>() {{add("StuffManager"); add("name"); add("tag"); }};
SettingsContainer = R.id.FragmentContainer2;
SettingsTag = getString(R.string.navdrawer_stuffmanager);
SettingsVariableFragment = new StuffManagerVariableFragment();
SettingsEmptyFragment = new StuffManagerEmptyFragment();
} else if (base.equalsIgnoreCase("GeneralSettings")) {
Data = new ArrayList<String>() {{add("GeneralSettings"); add("name"); add("ip"); add("port"); add("username"); add("pass"); }};
SettingsContainer = R.id.FragmentContainerGeneralSettings;
SettingsTag = getString(R.string.navdrawer_generalsettings);
SettingsVariableFragment = new GeneralSettingsVariableFragment();
SettingsEmptyFragment = new GeneralSettingsEmptyFragment();
} else {
Log.e(tag, "String Base not recognised");
return;
}
AmountOfEntries = dbHandler.returnArray(base, Data.get(1)).size();
FragmentManager fm = getFragmentManager().findFragmentByTag(SettingsTag).getChildFragmentManager();
if ((dbHandler.returnArray(base, Data.get(1))).size() == 0 ) {
// Log.d(tag, "SettingsContainer1: " + String.valueOf(SettingsContainer) + "; SettingsEmtpyFragment1: " + SettingsEmptyFragment + "; Base1: " + base);
fm.beginTransaction().add(SettingsContainer, SettingsEmptyFragment, (base + "EmptyFragment")).commit();
fm.executePendingTransactions();
return;
}
if (AmountOfEntries > 0) {
String EmptyFragName = (base + "EmptyFragment");
if ((fm.findFragmentByTag(EmptyFragName)) != null) {
fm.beginTransaction().remove(fm.findFragmentByTag(EmptyFragName)).commit();
fm.executePendingTransactions();
}
for (int i = 0; i < AmountOfEntries; i++) {
ArrayList<String> fragmentData = new ArrayList<>();
for (int k=1; k < Data.size(); k++) {
int j=k-1;
fragmentData.set(j, (dbHandler.returnArray(base, Data.get(k)).get(j)));
}
if (token.equalsIgnoreCase("edit")) {
LinearLayout linearLayout = (LinearLayout) findViewById(SettingsContainer);
linearLayout.removeAllViews();
DrawVariableFragments(base ,"draw");
} else if (token.equalsIgnoreCase("add")) {
if (fm.findFragmentByTag(fragmentData.get(i)) == null) {
fm.beginTransaction().add(SettingsContainer, SettingsVariableFragment, fragmentData.get(0)).commit();
fm.executePendingTransactions();
if (base.equalsIgnoreCase("StuffManager")) {
((StuffManagerVariableFragment) fm
.findFragmentByTag(fragmentData.get(i)))
.setText(fragmentData.get(0), fragmentData.get(1));
} else if (base.equalsIgnoreCase("GeneralSettings")) {
((GeneralSettingsVariableFragment) fm
.findFragmentByTag(fragmentData.get(i)))
.setText(fragmentData.get(0), fragmentData.get(1), fragmentData.get(2), fragmentData.get(3));
}
}
} else if (token.equalsIgnoreCase("draw")) {
fm.beginTransaction().add(SettingsContainer, SettingsVariableFragment, fragmentData.get(0)).commit();
fm.executePendingTransactions();
if (base.equalsIgnoreCase("StuffManager")) {
((StuffManagerVariableFragment) fm
.findFragmentByTag(fragmentData.get(i)))
.setText(fragmentData.get(0), fragmentData.get(1));
} else if (base.equalsIgnoreCase("GeneralSettings")) {
((GeneralSettingsVariableFragment) fm
.findFragmentByTag(fragmentData.get(i)))
.setText(fragmentData.get(0), fragmentData.get(1), fragmentData.get(2), fragmentData.get(3));
}
}
}
} else {
Log.d("TEST", "WTF, nameArray.size != 0 && !> 0");
}
}
}
GeneralSettingsFragment (Snippet)
package com.example.fragments.Settings;
public class GeneralSettingsFragment extends Fragment {
MainActivity ma;
DBHandler dbHandler;
private static Menu optionsMenu;
public static boolean hideDeleteAllButton = false;
LinearLayout linearLayout;
View rootView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_generalsettings, container, false);
ma = (MainActivity) getActivity();
linearLayout = (LinearLayout) rootView.findViewById(R.id.FragmentContainerGeneralSettings);
if (linearLayout == null) {
Log.e("GMF", "Layout is null");
} else if (linearLayout.getChildCount() == 0) {
GeneralSettingsInitialInputDialog GSIID = new GeneralSettingsInitialInputDialog();
GSIID.show(getFragmentManager(), "dialog");
hideDeleteAllButton = true;
} else {
hideDeleteAllButton = false;
}
ma.DrawVariableFragments("GeneralSettings", "draw");
return rootView;
}
}
You are still doing things in an unsupported way. In MainActivity.DrawVariableFragments() you are creating a new GeneralSettingsVariableFragment() and then call getChildFragmentManager() on it and attempt to commit a fragment.
The GeneralSettingsFragment has not yet been attached to an Activity so it does not have a host. This throws the IllegalStateException("Activity has been destroyed") exception you are seeing when you try to commit the FragmentTransaction.
It is unclear why you are creating a new GeneralSettingsVariableFragmentwhen you are already inside a new instance of one.
To properly lookup an existing fragment use getFragmentManager().findFragmentByTag(...) or getFragmentManager().findFragmentById(...).
program sudenly close when any edittext is left empty when ever i pressed a button to move to next to activity. here is the code.
package cme.ws.com.ws.cme;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
/**
* Created by Waqas Aamer on 5/27/2015.
*/
public class areaActivity extends Activity {
int plotarea, coveredarea;
int brickprice, blockprice, cementprice, sandprice, crushprice, ironprice;
int brickprice1, blockprice1, cementprice1, sandprice1, crushprice1, ironprice1;
int plotarea1, coveredarea1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_area);
{
final Context context = getApplicationContext();
final int duration = Toast.LENGTH_SHORT;
Button movenextarea=(Button) findViewById(R.id.buttonnextexteriorwall);
movenextarea.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = getIntent();
if (null != intent)
{
// test = intent.getStringExtra("NameOfVariable");
brickprice1 = intent.getIntExtra("anything00", brickprice);
blockprice1 = intent.getIntExtra("anything11", blockprice);
sandprice1 = intent.getIntExtra("anything22", sandprice);
ironprice1 = intent.getIntExtra("anything33", ironprice);
cementprice1 = intent.getIntExtra("anything44", cementprice);
crushprice1 = intent.getIntExtra("anything55", crushprice);
}
EditText areanumber1 = (EditText) findViewById(R.id.editTextplotarea);
if(areanumber1 == null)
{
Toast toast = Toast.makeText(context, "Please fill the plot area field ", duration);
toast.show();
}
else
{
plotarea1 = Integer.parseInt(areanumber1.getText().toString());
}
EditText areanumber2 = (EditText) findViewById(R.id.editTextcoveredarea);
if(areanumber2 == null)
{
Toast toast1 = Toast.makeText(context, "Please fill the covered area field ", duration);
toast1.show();
}
else
{
coveredarea1 = Integer.parseInt(areanumber2.getText().toString());
}
int sqrt = (int) Math.sqrt(plotarea1);
int oneside = sqrt;
Intent secondActivity = new Intent (getApplicationContext(), exteriorwallActivity.class);
secondActivity.putExtra("anything000", brickprice1);
secondActivity.putExtra("anything111", blockprice1);
secondActivity.putExtra("anything222", cementprice1);
secondActivity.putExtra("anything333", sandprice1);
secondActivity.putExtra("anything444", ironprice1);
secondActivity.putExtra("anything555", crushprice1);
secondActivity.putExtra("anything", oneside);
secondActivity.putExtra("anything1", coveredarea1);
startActivity(secondActivity);
}
});
}
}
}
i want this that whenver a edittext box is left empty .the variable in whcih it is storing that value automatically stores 0.
eroor log is
07-05 23:20:42.206 14348-14348/cme.ws.com.ws.cme E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NumberFormatException: unable to parse '' as integer
at java.lang.Integer.parseInt(Integer.java:412)
at java.lang.Integer.parseInt(Integer.java:382)
at cme.ws.com.ws.cme.areaActivity$1.onClick(areaActivity.java:52)
at android.view.View.performClick(View.java:2408)
at android.view.View$PerformClick.run(View.java:8816)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
Your EditText fields cannot be equals null because in previous line of your verification you have initialized them. Instead of using if (areanumber1 == null) and if (areanumber2 == null), check your EditText like this:
boolean isEmpty(EditText textField) {
return textField.getText().toString().trim().length() == 0;
}
If function return false means that EditText is not empty and return true means that EditText is empty.
This test...
if(areanumber1 == null)
does not check if the EditText called areanumber1 has no text. This checks if the variable named areanumber1 is a null reference. Hopefully it's not since you know what IDs your layout XML is using. What's happening is your code is trying to use parseInt() on an empty string.
You should instead do something like this:
String area1text = areanumber1.getText().toString(); // works even if empty
if (TextUtils.isEmpty(area1Text)) { // text is empty
plotarea1 = 0;
} else {
plotarea1 = Integer.parseInt(area1text);
}
TextUtils is an Android class with some useful static methods like the one I used above. Also, make sure your EditTexts are using the proper android:inputType to restrict the text to numbers only, or else the parseInt() will throw an exception.
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);
I just uploaded my app to google play and then installed it on my android phone which is running android 2.3.5. Anyways everything worked perfect on the emulator but crashes right on start up on the real device. Any ideas? here's the code.
public class StopWatch extends Activity implements OnClickListener {
//PROPERTIES USED THROUGHOUT CLASS
private Random rand = new Random();
private TextView stopWatchC;
private Button startButton,stopButton,resetButton;
private RelativeLayout mainLayout;
private Handler handle;
private Handler backHand = new Handler();
private boolean timerIsRunning;
private boolean previouslyStarted;
private long startTime;
private long endTime;
private long runTime;
private long UPDATE_EVERY = 200;
private int backgrounds[] = {
R.drawable.woman_1,
R.drawable.woman_2,
R.drawable.woman_3,
R.drawable.woman_4,
R.drawable.woman_5,
R.drawable.woman_6,
R.drawable.woman_7,
R.drawable.woman_8,
R.drawable.woman_9
};
//END PROPERTY DECLARATIONS
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stopwatch);
//Start our service
startService(new Intent(this,StopwatchService.class));
//SETUP BUTTON AND TEXTVIEWS
stopWatchC = (TextView) findViewById(R.id.counter);
startButton = (Button) findViewById(R.id.start_button);
stopButton = (Button) findViewById(R.id.stop_button);
resetButton = (Button) findViewById(R.id.reset);
mainLayout = (RelativeLayout) findViewById(R.id.main_layout);
//Handles listening for clicks on our start,stop and reset buttons
startButton.setOnClickListener(this);
stopButton.setOnClickListener(this);
resetButton.setOnClickListener(this);
//Calls run method for changing backgrounds
backHand.postDelayed(backgroundUpdate, 300);
}
/**
* Handles displaying the counter
*/
public void SWCounterDisplay()
{
String display;
long now;
long difference;
long secs;
long mins;
long hours;
if(timerIsRunning == true)
{
now = System.currentTimeMillis();
}else{
now = endTime;
}
if(previouslyStarted == true){
difference = runTime + (now - startTime);
}else{
difference = now-startTime;
}
//No negative numbers
if(difference < 0)
{
difference = 0;
}
secs = difference/1000;
mins = secs/60;
hours = mins/60;
secs = secs%60;
mins = mins%60;
display = String.format("%d", hours) + ":" +
String.format("%02d",mins) + ":" +
String.format("%02d", secs);
stopWatchC.setText(display);
}
/**
* Reset the timer
*/
public void resetTimer()
{
timerIsRunning = false;
previouslyStarted = false;
stopButton.setEnabled(false);
startButton.setEnabled(true);
runTime = 0;
SWCounterDisplay();
handle.removeCallbacks(timerUpdate);
handle = null;
}
/**
* Starts the stop watch
*/
public void startTimer()
{
timerIsRunning = true;
stopButton.setEnabled(timerIsRunning);
startButton.setEnabled(false);
if(!previouslyStarted){
previouslyStarted = true;
runTime = 0;
}
startTime = System.currentTimeMillis();
//Create new handler
handle = new Handler();
handle.postDelayed(timerUpdate, UPDATE_EVERY);
}
/**
* Stops the timer
*/
public void stopTimer()
{
timerIsRunning = false;
stopButton.setEnabled(timerIsRunning);
startButton.setEnabled(true);
endTime = System.currentTimeMillis();
runTime += endTime-startTime;
handle.removeCallbacks(timerUpdate);
handle = null;
}
/**
* Handles any onClick events
*/
#Override
public void onClick(View v) {
if(v == startButton)
{
startTimer();
}else if(v == stopButton)
{
stopTimer();
}else if(v == resetButton)
{
resetTimer();
}
}
/**
* Changes the background every 20 Seconds
*/
private Runnable backgroundUpdate = new Runnable(){
#Override
public void run() {
mainLayout.setBackgroundResource(backgrounds[rand.nextInt(backgrounds.length)]);
backHand.postDelayed(this, 60000);
}
};
/**
* Handles updating the timer
*/
private Runnable timerUpdate = new Runnable(){
#Override
public void run() {
SWCounterDisplay();
if(handle != null){
handle.postDelayed(this, UPDATE_EVERY);
}
}
};
/**
* Call run method if timer is still running
*/
public void onStart()
{
super.onStart();
if(timerIsRunning == true)
{
handle = new Handler();
handle.postDelayed(timerUpdate, UPDATE_EVERY);
}
}
/**
* Stop the timer if timer is still running
*/
public void onStop()
{
super.onStop();
if(timerIsRunning == true)
{
handle.removeCallbacks(timerUpdate);
handle = null;
}
}
/**
* Resume when the onResume method is called
*/
public void onResume()
{
super.onResume();
if(timerIsRunning == true){
stopButton.setEnabled(true);
startButton.setEnabled(false);
}else{
stopButton.setEnabled(false);
startButton.setEnabled(true);
}
SWCounterDisplay();
}
package com.webdeveloper93.stopwatch;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class StopwatchService extends Service {
#Override
public IBinder onBind(Intent arg0) {
return null;
}
public int onStartCommand(Intent intent,int flags,int startId)
{
Log.d("StopwatchService:","SERVICE STARTED");
super.onStartCommand(intent, flags, startId);
return START_NOT_STICKY;
}
public void onDestroy()
{
Log.d("StopwatchService:","SERVICE DESTROYED");
super.onDestroy();
}
}
Thanks in advance
EDIT
I/ActivityManager( 132): No longer want com.google.android.gsf.login (pid 1140): hidden #16
D/WifiService( 132): ACTION_BATTERY_CHANGED pluggedType: 0
I/ActivityManager( 132): Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.webdeveloper93.stopwatch/.StopWatch } from pid 231
E/AndroidRuntime( 1186): FATAL EXCEPTION: main
E/AndroidRuntime( 1186): java.lang.NoSuchMethodError: android.os.StrictMode$VmPolicy$Builder.detectLeakedClosableObjects
E/AndroidRuntime( 1186): at com.webdeveloper93.stopwatch.StopWatch.onCreate(StopWatch.java:59)
E/AndroidRuntime( 1186): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
E/AndroidRuntime( 1186): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
E/AndroidRuntime( 1186): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
E/AndroidRuntime( 1186): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
E/AndroidRuntime( 1186): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
E/AndroidRuntime( 1186): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime( 1186): at android.os.Looper.loop(Looper.java:130)
E/AndroidRuntime( 1186): at android.app.ActivityThread.main(ActivityThread.java:3683)
E/AndroidRuntime( 1186): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 1186): at java.lang.reflect.Method.invoke(Method.java:507)
E/AndroidRuntime( 1186): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864)
E/AndroidRuntime( 1186): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
E/AndroidRuntime( 1186): at dalvik.system.NativeStart.main(Native Method)
W/ActivityManager( 132): Force finishing activity com.webdeveloper93.stopwatch/.StopWatch
W/ActivityManager( 132): Activity pause timeout for HistoryRecord{408ff850 com.webdeveloper93.stopwatch/.StopWatch}
W/InputMethodManagerService( 132): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#405ca178
I/ActivityManager( 132): Process com.webdeveloper93.stopwatch (pid 1186) has died.
W/ActivityManager( 132): Service crashed 2 times, stopping: ServiceRecord{4078c080 com.webdeveloper93.stopwatch/.StopwatchService}
W/ActivityManager( 132): Activity destroy timeout for HistoryRecord{408ff850 com.webdeveloper93.stopwatch/.StopWatch}
I/ActivityManager( 132): Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=org.jtb.alogcat/.LogActivity } from pid 231
It looks like you use a method which is not implemented in android <=2.3.5. If you remove #SuppressLint("NewApi"), you will see which one it is.
I think it works in your emulator because you use a higher sdk-version there.