Hello guys I am making an Android app that convert from binary to decimal and I have made a class called Binary and a class called Decimal and a function in the Binary class that convert from decimal to binary
public Binary DtoB(Decimal decimal)
{
String temp = null;
do
{
if(decimal.decimal%2!=0)
temp+='1';
else
temp+='0';
decimal.decimal/=2;
}while(decimal.decimal>0);
while(temp.length()%4!=0)
temp+='0';
for(int i=temp.length()-1;i>=0;i--)
{
this.bn+=temp.charAt(i);
}
return this;
}
and in the activity there's a button that converts, but when I test and press on the button the app breaks
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
d1.decimal=Integer.parseInt(e1.getText().toString());
b.DtoB(d1);
t1.setText(b.bn);
}
});
can any one help me please ???
Here is the logcat:
10-26 09:16:15.831: E/AndroidRuntime(280): FATAL EXCEPTION: main
10-26 09:16:15.831: E/AndroidRuntime(280): java.lang.NullPointerException
10-26 09:16:15.831: E/AndroidRuntime(280): at com.example.converter.MainActivity$1.onClick(MainActivity.java:34)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.view.View.performClick(View.java:2408)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.view.View$PerformClick.run(View.java:8816)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.os.Handler.handleCallback(Handler.java:587)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.os.Handler.dispatchMessage(Handler.java:92)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.os.Looper.loop(Looper.java:123) 10-26 09:16:15.831: E/AndroidRuntime(280): at android.app.ActivityThread.main(ActivityThread.java:4627)
10-26 09:16:15.831: E/AndroidRuntime(280): at java.lang.reflect.Method.invokeNative(Native Method) 10-26 09:16:15.831: E/AndroidRuntime(280): at java.lang.reflect.Method.invoke(Method.java:521)
Try this...!
public class BinaryToDecimal {
public int getDecimalFromBinary(int binary){
int decimal = 0;
int power = 0;
while(true){
if(binary == 0){
break;
} else {
int tmp = binary%10;
decimal += tmp*Math.pow(2, power);
binary = binary/10;
power++;
}
}
return decimal;
}
public static void main(String a[]){
BinaryToDecimal bd = new BinaryToDecimal();
System.out.println("11 ===> "+bd.getDecimalFromBinary(11));
System.out.println("110 ===> "+bd.getDecimalFromBinary(110));
System.out.println("100110 ===> "+bd.getDecimalFromBinary(100110));
}
}
check variable all are initialize perfectly . because some time objectc are created but it is null so can't work and throw java.lang.NullPointerException .....
b1 , d1 , b ,t1
Related
I am trying to send my web service response from one activity to another .when I move one activity to another activity without response it work fine .but when I send response it give me error .could you please help me removing this exception ..
Actually I am sending like this:I think problem in this line i.putExtra("test", data);
I do like this..
10-25 21:13:47.619: E/AndroidRuntime(962): FATAL EXCEPTION: main
10-25 21:13:47.619: E/AndroidRuntime(962): java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.firstgroup.applicationload/com.firstgroup.ui.screens.Departuredashboardscreen}: java.lang.NullPointerException
10-25 21:13:47.619: E/AndroidRuntime(962): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
10-25 21:13:47.619: E/AndroidRuntime(962): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
10-25 21:13:47.619: E/AndroidRuntime(962): at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-25 21:13:47.619: E/AndroidRuntime(962): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
10-25 21:13:47.619: E/AndroidRuntime(962): at android.os.Handler.dispatchMessage(Handler.java:99)
10-25 21:13:47.619: E/AndroidRuntime(962): at android.os.Looper.loop(Looper.java:137)
10-25 21:13:47.619: E/AndroidRuntime(962): at android.app.ActivityThread.main(ActivityThread.java:5041)
10-25 21:13:47.619: E/AndroidRuntime(962): at java.lang.reflect.Method.invokeNative(Native Method)
10-25 21:13:47.619: E/AndroidRuntime(962): at java.lang.reflect.Method.invoke(Method.java:511)
10-25 21:13:47.619: E/AndroidRuntime(962): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-25 21:13:47.619: E/AndroidRuntime(962): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-25 21:13:47.619: E/AndroidRuntime(962): at dalvik.system.NativeStart.main(Native Method)
10-25 21:13:47.619: E/AndroidRuntime(962): Caused by: java.lang.NullPointerException
10-25 21:13:47.619: E/AndroidRuntime(962): at android.os.Parcel.readListInternal(Parcel.java:2237)
10-25 21:13:47.619: E/AndroidRuntime(962): at android.os.Parcel.readList(Parcel.java:1531)
10-25 21:13:47.619: E/AndroidRuntime(962): at com.firstgroup.dto.deparaturedaseboarddto.<init>(deparaturedaseboarddto.java:209)
10-25 21:13:47.619: E/AndroidRuntime(962): at com.firstgroup.dto.deparaturedaseboarddto.<init>(deparaturedaseboarddto.java:193)
10-25 21:13:47.619: E/AndroidRuntime(962): at com.firstgroup.dto.deparaturedaseboarddto$1.createFromParcel(deparaturedaseboarddto.java:185)
10-25 21:13:47.619: E/AndroidRuntime(962): at com.firstgroup.dto.deparaturedaseboarddto$1.createFromParcel(deparaturedaseboarddto.java:1)
10-25 21:13:47.619: E/AndroidRuntime(962): at android.os.Parcel.readParcelable(Parcel.java:2103)
10-25 21:13:47.619: E/AndroidRuntime(962): at android.os.Parcel.readValue(Parcel.java:1965)
10-25 21:13:47.619: E/AndroidRuntime(962): at android.os.Parcel.readMapInternal(Parcel.java:2226)
10-25 21:13:47.619: E/AndroidRuntime(962): at android.os.Bundle.unparcel(Bundle.java:223)
10-25 21:13:47.619: E/AndroidRuntime(962): at android.os.Bundle.getParcelable(Bundle.java:1173)
10-25 21:13:47.619: E/AndroidRuntime(962): at android.content.Intent.getParcelableExtra(Intent.java:4330)
10-25 21:13:47.619: E/AndroidRuntime(962): at com.firstgroup.ui.screens.Departuredashboardscreen.onCreate(Departuredashboardscreen.java:21)
10-25 21:13:47.619: E/AndroidRuntime(962): at android.app.Activity.performCreate(Activity.java:5104)
10-25 21:13:47.619: E/AndroidRuntime(962): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
10-25 21:13:47.619: E/AndroidRuntime(962): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
10-25 21:13:47.619: E/AndroidRuntime(962): ... 11 more
#Override
public void getWebserviceResponse(String result) {
// TODO Auto-generated method stub
//JSONObject js=new Jso(result);
deparaturedaseboarddto data = new Gson().fromJson(result, deparaturedaseboarddto.class);
/*listView=(ListView)findViewById(R.id.listView1);
adapter = new CustomListAdapter(this, data.getData());
listView.setAdapter(adapter);*/
Intent i = new Intent(Appliacationload.this,Departuredashboardscreen.class);
i.putExtra("test", data);
startActivity(i);
finish();
Log.d("----", "========");
}
Second Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.departure_dashboard);
Intent i = getIntent();
deparaturedaseboarddto myParcelableObject = (deparaturedaseboarddto) i.getParcelableExtra("test");
Log.d("===", "hhhh");
}
**Model class :**
public class deparaturedaseboarddto implements Parcelable{
ArrayList<deparaturedaseboarddto> data;
public ArrayList<deparaturedaseboarddto> getData() {
return data;
}
public void setData(ArrayList<deparaturedaseboarddto> data) {
this.data = data;
}
#SerializedName("alertsId")
int alertsId;
#SerializedName("destExpArrival")
String destExpArrival;
#SerializedName("destSchArrival")
String destSchArrival;
#SerializedName("expDepart")
String expDepart;
#SerializedName("filteredStation")
String filteredStation;
#SerializedName("platformNo")
String platformNo;
#SerializedName("rid")
String rid;
#SerializedName("schDepart")
String schDepart;
#SerializedName("toc")
String toc;
#SerializedName("toExpArrival")
String toExpArrival;
#SerializedName("toSchArrival")
String toSchArrival;
#SerializedName("trainID")
String trainID;
#SerializedName("trainLastReportedAt")
String trainLastReportedAt;
#SerializedName("destinationStation")
DestinationStation destinationStation;
public deparaturedaseboarddto(String trainID,String toc,String trainLastReportedAt, String platformNo, String schDepart, String expDepart, int alertsId, String rid, String destSchArrival, String filteredStation, String destExpArrival, String toSchArrival, String toExpArrival,DestinationStation destinationStation){
super();
this.trainID=trainID;
this.toc=toc;
this.trainLastReportedAt=trainLastReportedAt;
this.platformNo=platformNo;
this.schDepart=schDepart;
this.expDepart=expDepart;
this.alertsId=alertsId;
this.destinationStation=destinationStation;
this.toExpArrival=toExpArrival;
this.toSchArrival=toSchArrival;
this.destExpArrival=destExpArrival;
this.filteredStation=filteredStation;
this.destSchArrival=destSchArrival;
this.rid=rid;
}
public DestinationStation getDestinationStation() {
return destinationStation;
}
public void setDestinationStation(DestinationStation destinationStation) {
this.destinationStation = destinationStation;
}
public int getAlertsId() {
return alertsId;
}
public void setAlertsId(int alertsId) {
this.alertsId = alertsId;
}
public String getDestExpArrival() {
return destExpArrival;
}
public void setDestExpArrival(String destExpArrival) {
this.destExpArrival = destExpArrival;
}
public String getDestSchArrival() {
return destSchArrival;
}
public void setDestSchArrival(String destSchArrival) {
this.destSchArrival = destSchArrival;
}
public String getExpDepart() {
return expDepart;
}
public void setExpDepart(String expDepart) {
this.expDepart = expDepart;
}
public String getFilteredStation() {
return filteredStation;
}
public void setFilteredStation(String filteredStation) {
this.filteredStation = filteredStation;
}
public String getPlatformNo() {
return platformNo;
}
public void setPlatformNo(String platformNo) {
this.platformNo = platformNo;
}
public String getRid() {
return rid;
}
public void setRid(String rid) {
this.rid = rid;
}
public String getSchDepart() {
return schDepart;
}
public void setSchDepart(String schDepart) {
this.schDepart = schDepart;
}
public String getToc() {
return toc;
}
public void setToc(String toc) {
this.toc = toc;
}
public String getToExpArrival() {
return toExpArrival;
}
public void setToExpArrival(String toExpArrival) {
this.toExpArrival = toExpArrival;
}
public String getToSchArrival() {
return toSchArrival;
}
public void setToSchArrival(String toSchArrival) {
this.toSchArrival = toSchArrival;
}
public String getTrainID() {
return trainID;
}
public void setTrainID(String trainID) {
this.trainID = trainID;
}
public String getTrainLastReportedAt() {
return trainLastReportedAt;
}
public void setTrainLastReportedAt(String trainLastReportedAt) {
this.trainLastReportedAt = trainLastReportedAt;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(alertsId);
dest.writeString(destExpArrival);
dest.writeString(destSchArrival);
dest.writeString(expDepart);
dest.writeString(filteredStation);
dest.writeString(platformNo);
dest.writeString(rid);
dest.writeString(schDepart);
dest.writeString(toc);
dest.writeString(toExpArrival);
dest.writeString(toSchArrival);
dest.writeString(trainID);
dest.writeString(trainLastReportedAt);
dest.writeParcelable(this.destinationStation, flags);
dest.writeList(data);
}
public static final Parcelable.Creator<deparaturedaseboarddto> CREATOR = new Parcelable.Creator<deparaturedaseboarddto>() {
public deparaturedaseboarddto createFromParcel(Parcel in) {
return new deparaturedaseboarddto(in);
}
public deparaturedaseboarddto[] newArray(int size) {
return new deparaturedaseboarddto[size];
}
};
private deparaturedaseboarddto(Parcel in) {
this.alertsId=in.readInt();
this.destExpArrival=in.readString();
this.destSchArrival=in.readString();
this.expDepart=in.readString();
this.filteredStation=in.readString();
this.platformNo=in.readString();
this.rid=in.readString();
this.schDepart=in.readString();
this.toc=in.readString();
this.toExpArrival=in.readString();
this.toSchArrival=in.readString();
this.trainID=in.readString();
this.trainLastReportedAt=in.readString();
this.destinationStation = in.readParcelable(DestinationStation.class.getClassLoader());
in.readList(data,deparaturedaseboarddto.class.getClassLoader());
}
}
package com.firstgroup.dto;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.SerializedName;
public class DestinationStation implements Parcelable {
#SerializedName("crsCode")
String crsCode;
#SerializedName("stationName")
String stationName;
public DestinationStation(String crsCode, String stationName) {
// TODO Auto-generated constructor stub
super();
this.crsCode=crsCode;
this.stationName=stationName;
}
public String getCrsCode() {
return crsCode;
}
public void setCrsCode(String crsCode) {
this.crsCode = crsCode;
}
public String getStationName() {
return stationName;
}
public void setStationName(String stationName) {
this.stationName = stationName;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(crsCode);
dest.writeString(stationName);
}
public static final Parcelable.Creator<DestinationStation> CREATOR = new Parcelable.Creator<DestinationStation>() {
public DestinationStation createFromParcel(Parcel in) {
return new DestinationStation(in);
}
public DestinationStation[] newArray(int size) {
return new DestinationStation[size];
}
};
private DestinationStation(Parcel in) {
this.crsCode=in.readString();
this.stationName=in.readString();
}
}
Updated one..
#Override
public void getWebserviceResponse(String result) {
// TODO Auto-generated method stub
//JSONObject js=new Jso(result);
deparaturedaseboarddto data = new Gson().fromJson(result, deparaturedaseboarddto.class);
/*listView=(ListView)findViewById(R.id.listView1);
adapter = new CustomListAdapter(this, data.getData());
listView.setAdapter(adapter);*/
Intent i = new Intent(Appliacationload.this,Departuredashboardscreen.class);
EventBus.getDefault().postSticky(data);
//i.putExtra("test", (Parcelable)data);
startActivity(i);
finish();
Log.d("----", "========");
}
Next Activity:
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.departure_dashboard);
Intent i = getIntent();
deparaturedaseboarddto myParcelableObject = (deparaturedaseboarddto) EventBus.getDefault().getStickyEvent(deparaturedaseboarddto.class);
Log.d("===", "hhhh");
}
Exception:
10-26 00:56:36.052: E/AndroidRuntime(806): FATAL EXCEPTION: AsyncTask #3
10-26 00:56:36.052: E/AndroidRuntime(806): java.lang.RuntimeException: An error occured while executing doInBackground()
10-26 00:56:36.052: E/AndroidRuntime(806): at android.os.AsyncTask$3.done(AsyncTask.java:299)
10-26 00:56:36.052: E/AndroidRuntime(806): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
10-26 00:56:36.052: E/AndroidRuntime(806): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
10-26 00:56:36.052: E/AndroidRuntime(806): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
10-26 00:56:36.052: E/AndroidRuntime(806): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
10-26 00:56:36.052: E/AndroidRuntime(806): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
10-26 00:56:36.052: E/AndroidRuntime(806): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
10-26 00:56:36.052: E/AndroidRuntime(806): at java.lang.Thread.run(Thread.java:856)
10-26 00:56:36.052: E/AndroidRuntime(806): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
10-26 00:56:36.052: E/AndroidRuntime(806): at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:4746)
10-26 00:56:36.052: E/AndroidRuntime(806): at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:823)
10-26 00:56:36.052: E/AndroidRuntime(806): at android.view.View.requestLayout(View.java:15473)
10-26 00:56:36.052: E/AndroidRuntime(806): at android.view.View.setFlags(View.java:8444)
10-26 00:56:36.052: E/AndroidRuntime(806): at android.view.View.setVisibility(View.java:5716)
10-26 00:56:36.052: E/AndroidRuntime(806): at android.app.Dialog.hide(Dialog.java:294)
10-26 00:56:36.052: E/AndroidRuntime(806): at com.firstgroup.webservice.RequestTask.doInBackground(RequestTask.java:66)
10-26 00:56:36.052: E/AndroidRuntime(806): at com.firstgroup.webservice.RequestTask.doInBackground(RequestTask.java:1)
10-26 00:56:36.052: E/AndroidRuntime(806): at android.os.AsyncTask$2.call(AsyncTask.java:287)
10-26 00:56:36.052: E/AndroidRuntime(806): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
10-26 00:56:36.052: E/AndroidRuntime(806): ... 4 more
10-26 00:56:40.424: E/WindowManager(806): Activity com.firstgroup.applicationload.Appliacationload has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40f6b308 G.E..... R.....ID 0,0-729,324} that was originally added here
10-26 00:56:40.424: E/WindowManager(806): android.view.WindowLeaked: Activity com.firstgroup.applicationload.Appliacationload has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40f6b308 G.E..... R.....ID 0,0-729,324} that was originally added here
10-26 00:56:40.424: E/WindowManager(806): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:354)
10-26 00:56:40.424: E/WindowManager(806): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216)
10-26 00:56:40.424: E/WindowManager(806): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
10-26 00:56:40.424: E/WindowManager(806): at android.app.Dialog.show(Dialog.java:281)
10-26 00:56:40.424: E/WindowManager(806): at com.firstgroup.webservice.RequestTask.onPreExecute(RequestTask.java:36)
10-26 00:56:40.424: E/WindowManager(806): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
10-26 00:56:40.424: E/WindowManager(806): at android.os.AsyncTask.execute(AsyncTask.java:534)
10-26 00:56:40.424: E/WindowManager(806): at com.firstgroup.applicationload.Appliacationload.calldeparutureWebservice(Appliacationload.java:130)
10-26 00:56:40.424: E/WindowManager(806): at com.firstgroup.applicationload.Appliacationload.access$1(Appliacationload.java:126)
10-26 00:56:40.424: E/WindowManager(806): at com.firstgroup.applicationload.Appliacationload$2.onClick(Appliacationload.java:91)
10-26 00:56:40.424: E/WindowManager(806): at android.view.View.performClick(View.java:4204)
10-26 00:56:40.424: E/WindowManager(806): at android.view.View$PerformClick.run(View.java:17355)
10-26 00:56:40.424: E/WindowManager(806): at android.os.Handler.handleCallback(Handler.java:725)
10-26 00:56:40.424: E/WindowManager(806): at android.os.Handler.dispatchMessage(Handler.java:92)
10-26 00:56:40.424: E/WindowManager(806): at android.os.Looper.loop(Looper.java:137)
10-26 00:56:40.424: E/WindowManager(806): at android.app.ActivityThread.main(ActivityThread.java:5041)
10-26 00:56:40.424: E/WindowManager(806): at java.lang.reflect.Method.invokeNative(Native Method)
10-26 00:56:40.424: E/WindowManager(806): at java.lang.reflect.Method.invoke(Method.java:511)
10-26 00:56:40.424: E/WindowManager(806): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-26 00:56:40.424: E/WindowManager(806): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-26 00:56:40.424: E/WindowManager(806): at dalvik.system.NativeStart.main(Native Method)
Should be something like this:
#Override
public void getWebserviceResponse(String result) {
// TODO Auto-generated method stub
//JSONObject js=new Jso(result);
deparaturedaseboarddto data = new Gson().fromJson(result, deparaturedaseboarddto.class);
/*listView=(ListView)findViewById(R.id.listView1);
adapter = new CustomListAdapter(this, data.getData());
listView.setAdapter(adapter);*/
Intent i = new Intent(Appliacationload.this,Departuredashboardscreen.class);
//i.putExtra("test", data);
EventBus.getDefault().postSticky(deparaturedaseboarddto);
startActivity(i);
finish();
Log.d("----", "========");
}
and in Departuredashboardscreen
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.departure_dashboard);
deparaturedaseboarddto myParcelableObject = EventBus.getDefault().getStickyEvent(deparaturedaseboarddto.class);
Log.d("===", "hhhh");
}
Try using getExtra()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.departure_dashboard);
//use getExtra()
Intent i = getIntent().getExtras();
deparaturedaseboarddto myParcelableObject =
(deparaturedaseboarddto) i.getParcelableExtra("test");
Log.d("===", "hhhh");
}
I'm implementing to show dialog box when Internet is offline, when i run my app i got "FATAL Exception main" and ClassCastException when when i click on button and application is crash . Can someone tell me what i am doing wrong ? Thanks to you in Advanced.
here is code how i check is internet enabled or not:
public class AndroidDetectInternetConnectionActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnStatus = (Button) findViewById(R.id.btn_check);
btnStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!isOnline())
{
showNoConnectionDialog(this);
}
}
});
}
public static void showNoConnectionDialog(OnClickListener onClickListener)
{
final Context ctx = (Context) onClickListener;
AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
builder.setCancelable(true);
builder.setMessage(R.string.no_connection);
builder.setTitle(R.string.no_connection_title);
builder.setPositiveButton(R.string.settings_button_text, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
ctx.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
}
});
builder.setNegativeButton(R.string.cancel_button_text, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
return;
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog) {
return;
}
});
builder.show();
}
public boolean isOnline()
{
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting())
{
return true;
}
return false;
}
}
// This is my Log Cat stack trace
11-15 11:57:19.115: D/AndroidRuntime(453): Shutting down VM
11-15 11:57:19.115: W/dalvikvm(453): threadid=1: thread exiting with uncaught exception (group=0x40015560)
11-15 11:57:19.122: E/AndroidRuntime(453): FATAL EXCEPTION: main
11-15 11:57:19.122: E/AndroidRuntime(453): java.lang.ClassCastException: com.example.detectinternetconnection.AndroidDetectInternetConnectionActivity$1
11-15 11:57:19.122: E/AndroidRuntime(453): at com.example.detectinternetconnection.AndroidDetectInternetConnectionActivity.showNoConnectionDialog(AndroidDetectInternetConnectionActivity.java:99)
11-15 11:57:19.122: E/AndroidRuntime(453): at com.example.detectinternetconnection.AndroidDetectInternetConnectionActivity$1.onClick(AndroidDetectInternetConnectionActivity.java:64)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.view.View.performClick(View.java:2485)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.view.View$PerformClick.run(View.java:9080)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.os.Handler.handleCallback(Handler.java:587)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.os.Handler.dispatchMessage(Handler.java:92)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.os.Looper.loop(Looper.java:123)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.app.ActivityThread.main(ActivityThread.java:3683)
11-15 11:57:19.122: E/AndroidRuntime(453): at java.lang.reflect.Method.invokeNative(Native Method)
11-15 11:57:19.122: E/AndroidRuntime(453): at java.lang.reflect.Method.invoke(Method.java:507)
11-15 11:57:19.122: E/AndroidRuntime(453): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11-15 11:57:19.122: E/AndroidRuntime(453): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
11-15 11:57:19.122: E/AndroidRuntime(453): at dalvik.system.NativeStart.main(Native Method)
11-15 11:57:24.892: I/Process(453): Sending signal. PID: 453 SIG: 9
change this line
final Context ctx = (Context) onClickListener;
to below one
final Context ctx = AndroidDetectInternetConnectionActivity.this;
basically you are trying to conver onClickListener to Contex which is incorrect and can not be casted.
Either you directly use ActivityName.this wherever you need context instance, or define static Context ctx as a class variable and intialize it in onCreate()by just adding this line ctx =this also remember to intialize it before using it.
Enjoy
There are two ways to solve this problem.
1) showNoConnectionDialog(this); and later on:
public static void showNoConnectionDialog(Context ctx) ...
2) showNoConnectionDialog(); and later on: public void showNoConnectionDialog() { Context ctx = AndroidDetectInternetConnectionActivity.this
You basic problem is generated by the line:
final Context ctx = (Context) onClickListener;
This is simply not a context so trying to force it to be one doesn't work.
I believe that you wanted to do was pass a context (or activity) to this function (as opposed to the local unnamed OnClickListener class that you are now passing)
The easiest solution would be to simple not pass anything to the constructor and use AndroidDetectInternetConnectionActivity.this to access your valid context.
I am very new to android. I have a counter on some SomeActivity, but when I get to the page corresponding to SomeActivity, my app crashes :
final TextView counter = (TextView) findViewById(R.id.laws_counter);
ImageView handDown = (ImageView) findViewById(R.id.handViewDown);
counter.setText("" + 0);
I want that on click of the handown, the counter is idented by -1. Here's
handDown.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(NewsActivity.this,
"The favorite list would appear on clicking this icon",
Toast.LENGTH_LONG).show();
setDown();
}
private void setDown() {
String count = counter.getText().toString();
int now_count = Integer.parseInt(count) +1;
counter.setText(String.valueOf(now_count));
}
});
Is this code correct ?
Update : here's the logcat
10-22 00:18:05.579: ERROR/AndroidRuntime(378): FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.donnfelker.android.bootstrap/com.donnfelker.android.bootstrap.ui.NewsActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
at android.app.ActivityThread.access$1500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.donnfelker.android.bootstrap.ui.NewsActivity.onCreate(NewsActivity.java:41)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
... 11 more
There are many ways that you can implement that functionality but think this would be an easy solution.
Make a helper method:
public class PreferencesData {
public static void saveInt(Context context, String key, int value) {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context);
sharedPrefs.edit().putInt(key, value).commit();
}
public static int getInt(Context context, String key, int defaultValue) {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context);
return sharedPrefs.getInt(key, defaultValue);
}
}
Then simply call the putInt method to save the counter in any Activity and getInt to get it again in any other Activity. As long as you use the same key both places.
I am making an android app. and am trying to fetching data from column, name and score from
the database table but getting this error at run time,
Sorry this application has stopped unexpectedly.
This is my Code from Database Class,
public long addscore(String name, int score)
{
ContentValues values = new ContentValues();
values.put(KEY_name, name);
values.put(KEY_score, score);
// Inserting Row
return db.insert(DATABASE_TABLE, null, values);
}
public Cursor getScore(long rowId) throws SQLException
{
Cursor mCursor = db.query(true,DATABASE_TABLE, new String[] {
KEY_scoreid,KEY_name,KEY_score },,KEY_scoreid + "="
+ rowid,null,null,null,null,null);
if (mCursor != null)
{
mCursor.moveToFirst();
}
return mCursor;
}
And this is the code of class from where i m trying to
fetch the Data from Database table (Highscore.java),
public class Highscore extends Activity
{
TextView name1,name2,name3,name4,name5,score1,score2,score3,score4,score5;
DBAdapter db1;
Cursor c;
int id;
String n1,n2,n3,n4,n5;
String s1,s2,s3,s4,s5;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.highscore);
Button backbtn=(Button)findViewById(R.id.backbtn);
OnClickListener listener=new OnClickListener()
{
public void onClick(View v)
{
Intent i=new Intent(Highscore.this,MainActivity.class);
startActivity(i);
finish();
}
};
backbtn.setOnClickListener(listener);
id=1;
name1=(TextView)findViewById(R.id.name1);
score1=(TextView)findViewById(R.id.score1);
db1=new DBAdapter(this);
db1.open();
c=db1.getScore(1);
n1=c.getString(1);
name1.setText(n1);
s1=c.getString(2);
score1.setText(s1);
c=db1.getScore(2);
n2=c.getString(1);
name2.setText(n2);
s2=c.getString(2);
score2.setText(s2);
c=db1.getScore(3);
n3=c.getString(1);
name3.setText(n3);
s3=c.getString(2);
score3.setText(s3);
id++;
c=db1.getScore(4);
n4=c.getString(1);
name4.setText(n4);
s4=c.getString(2);
score4.setText(s4);
id++;
c=db1.getScore(5);
n5=c.getString(1);
name5.setText(n5);
s5=c.getString(2);
score5.setText(s5);
c.deactivate();
c.close();
db1.close();
}
}
This time i am only fetching 5 names and scores.
Here's my Logcat Error,
09-19 12:01:36.046: D/AndroidRuntime(455): Shutting down VM
09-19 12:01:36.046: W/dalvikvm(455): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
09-19 12:01:36.066: E/AndroidRuntime(455): FATAL EXCEPTION: main
09-19 12:01:36.066: E/AndroidRuntime(455): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.quizapp/com.example.quizapp.Highscore}: java.lang.NullPointerException
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.os.Handler.dispatchMessage(Handler.java:99)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.os.Looper.loop(Looper.java:123)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread.main(ActivityThread.java:4627)
09-19 12:01:36.066: E/AndroidRuntime(455): at java.lang.reflect.Method.invokeNative(Native Method)
09-19 12:01:36.066: E/AndroidRuntime(455): at java.lang.reflect.Method.invoke(Method.java:521)
09-19 12:01:36.066: E/AndroidRuntime(455): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-19 12:01:36.066: E/AndroidRuntime(455): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-19 12:01:36.066: E/AndroidRuntime(455): at dalvik.system.NativeStart.main(Native Method)
09-19 12:01:36.066: E/AndroidRuntime(455): Caused by: java.lang.NullPointerException
09-19 12:01:36.066: E/AndroidRuntime(455): at com.example.quizapp.Highscore.onCreate(Highscore.java:59)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
09-19 12:01:36.066: E/AndroidRuntime(455): ... 11 more
If you people are not getting any thing from my question so please ask..
Please help me to Solve out the Error.
Thanks in Advance
From what I see you problem is not in the database connection, you have some untreated exceptions. You have a NULL pointer exception also in onCreate(Highscore.java:59)
You can do a thing: comment parts of the code until you get a working app(that does nothing) and then uncomment until you find the exact code that crashes the app, it is easy to do and usually you will find the line that is problematic
Good luck
Use this code insted of your.....
public Cursor getScore(long rowId) throws SQLException
{
Cursor mCursor = db.query(true,DATABASE_TABLE, new String[] {
KEY_scoreid,KEY_name,KEY_score },KEY_scoreid + " ='"
+ rowid + "'",null,null,null,null,null);
if (mCursor != null)
{
mCursor.moveToFirst();
}
return mCursor;
}
Hi, I try to check network connectivity and Internet present by using following method
check = new ConnectionDetector(getApplicationContext());
conn = check.isConnectingToInternet();
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context){
this._context = context;
}
/**
* Checking for all possible internet providers
* **/
/*public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}*/
public boolean isConnectingToInternet(){
try{
ConnectivityManager cm = (ConnectivityManager)_context.getSystemService
(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
Log.d("NetInfo", String.valueOf(netInfo));
if (netInfo != null && netInfo.isConnected())
{
//Network is available but check if we can get access from the network.
URL url = new URL("http://www.Google.com/");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(2000); // Timeout 2 seconds.
urlc.connect();
Log.d("NetInfo Response Code", String.valueOf(urlc.getResponseCode()));
// Toast.makeText(getApplicationContext(), String.valueOf(urlc.getResponseCode()), Toast.LENGTH_LONG).show();
if (urlc.getResponseCode() == 200) //Successful response.
{
return true;
}
else
{
Log.d("NO INTERNET", "NO INTERNET");
return false;
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return false;
}
}
Note :
But this will return NetworkOnMainThread Exception like follows.kindly any one suggest me what mistakes i made.......
03-27 12:53:35.617: W/System.err(1095): android.os.NetworkOnMainThreadException
03-27 12:53:35.627: W/System.err(1095): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1084)
03-27 12:53:35.637: W/System.err(1095): at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
03-27 12:53:35.637: W/System.err(1095): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
03-27 12:53:35.647: W/System.err(1095): at java.net.InetAddress.getAllByName(InetAddress.java:220)
03-27 12:53:35.647: W/System.err(1095): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:71)
03-27 12:53:35.657: W/System.err(1095): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
03-27 12:53:35.668: W/System.err(1095): at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:351)
03-27 12:53:35.668: W/System.err(1095): at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:86)
03-27 12:53:35.677: W/System.err(1095): at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
03-27 12:53:35.687: W/System.err(1095): at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:308)
03-27 12:53:35.699: W/System.err(1095): at libcore.net.http.HttpEngine.connect(HttpEngine.java:303)
03-27 12:53:35.699: W/System.err(1095): at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282)
03-27 12:53:35.707: W/System.err(1095): at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232)
03-27 12:53:35.718: W/System.err(1095): at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
03-27 12:53:35.727: W/System.err(1095): at com.slet.routemytrips.beta.ConnectionDetector.isConnectingToInternet(ConnectionDetector.java:50)
03-27 12:53:35.727: W/System.err(1095): at com.slet.routemytrips.beta.Disclaimer$1.onClick(Disclaimer.java:178)
03-27 12:53:35.738: W/System.err(1095): at android.view.View.performClick(View.java:3480)
03-27 12:53:35.738: W/System.err(1095): at android.view.View$PerformClick.run(View.java:13983)
03-27 12:53:35.748: W/System.err(1095): at android.os.Handler.handleCallback(Handler.java:605)
03-27 12:53:35.757: W/System.err(1095): at android.os.Handler.dispatchMessage(Handler.java:92)
03-27 12:53:35.757: W/System.err(1095): at android.os.Looper.loop(Looper.java:137)
03-27 12:53:35.767: W/System.err(1095): at android.app.ActivityThread.main(ActivityThread.java:4340)
03-27 12:53:35.777: W/System.err(1095): at java.lang.reflect.Method.invokeNative(Native Method)
03-27 12:53:35.777: W/System.err(1095): at java.lang.reflect.Method.invoke(Method.java:511)
03-27 12:53:35.787: W/System.err(1095): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
03-27 12:53:35.797: W/System.err(1095): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
03-27 12:53:35.807: W/System.err(1095): at dalvik.system.NativeStart.main(Native Method)
03-27 12:57:05.237: D/dalvikvm(90): GC_CONCURRENT freed 666K, 10% free 12624K/14023K, paused 6ms+10ms
You can't make HTTP requests on the main thread, it would cause the UI to freeze up. So it throws that exception. You need to do it in an AsyncTask or another Thread.
http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html
NetworkOnMainThreadException is thrown if you attempt to make a network request in the main UI Thread. So all network related operation should be done on the background thread.
AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as Executor, ThreadPoolExecutor and FutureTask.
http://developer.android.com/reference/android/os/AsyncTask.html
class TheTask extends AsyncTask<Void,Void,Void>
{
protected void onPreExecute()
{ super.onPreExecute();
//display progressdialog.
}
protected void doInBackground(Void ...params)
{
//http request. do not update ui here
return null;
}
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
//dismiss progressdialog.
//update ui
}
}
An alternative to asynctask is Robospice. Can make multiple spice request. Notifies on the ui thread. https://github.com/octo-online/robospice
To check Netowrk Connectivity.
In your activity
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if(CheckNetwork.isInternetAvailable(MainActivity.this))
{
//call asyntask and make http request.
}
}
CheckNetwork class
public class CheckNetwork {
private static final String TAG = CheckNetwork.class.getSimpleName();
public static boolean isInternetAvailable(Context context)
{
NetworkInfo info = (NetworkInfo) ((ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info == null)
{
Log.d(TAG,"no internet connection");
return false;
}
else
{
if(info.isConnected())
{
Log.d(TAG," internet connection available...");
return true;
}
else
{
Log.d(TAG," internet connection");
return true;
}
}
}
}