this is the code...plz let me know where did i go wrong.. also i am setting an adapter to the listview which is conatined in the View v1 inflated...this is all done in the extension response of a smartfox server...and then the following process on UI Thread..
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
alert();
}
});
public void alert(){
AlertDialog.Builder ab=new AlertDialog.Builder(RegActivity.this);
LayoutInflater linf=(LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View v1=linf.inflate(R.layout.proj_list, null);
ab.setView(v1);
ab.setTitle("Select a group");
ListView lvprojlist=(ListView) findViewById(R.id.projdisplaylist);
adplist=new ArrayAdapter<String>(RegActivity.this, R.layout.list_item, R.id.rowtext, projlist);
lvprojlist.setAdapter(adplist);
ab.setCancelable(false).setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
ab.create();
ab.show();
}
this is my logcat output..
12-19 17:14:33.869: W/dalvikvm(699): threadid=1: thread exiting with uncaught exception (group=0x40015560)
12-19 17:14:33.889: E/AndroidRuntime(699): FATAL EXCEPTION: main
12-19 17:14:33.889: E/AndroidRuntime(699): java.lang.NullPointerException
12-19 17:14:33.889: E/AndroidRuntime(699): at com.registersfsmodule.RegActivity.alert(RegActivity.java:392)
12-19 17:14:33.889: E/AndroidRuntime(699): at com.registersfsmodule.RegActivity$3$2.run(RegActivity.java:178)
12-19 17:14:33.889: E/AndroidRuntime(699): at android.os.Handler.handleCallback(Handler.java:587)
12-19 17:14:33.889: E/AndroidRuntime(699): at android.os.Handler.dispatchMessage(Handler.java:92)
12-19 17:14:33.889: E/AndroidRuntime(699): at android.os.Looper.loop(Looper.java:130)
12-19 17:14:33.889: E/AndroidRuntime(699): at android.app.ActivityThread.main(ActivityThread.java:3683)
12-19 17:14:33.889: E/AndroidRuntime(699): at java.lang.reflect.Method.invokeNative(Native Method)
12-19 17:14:33.889: E/AndroidRuntime(699): at java.lang.reflect.Method.invoke(Method.java:507)
12-19 17:14:33.889: E/AndroidRuntime(699): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-19 17:14:33.889: E/AndroidRuntime(699): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-19 17:14:33.889: E/AndroidRuntime(699): at dalvik.system.NativeStart.main(Native Method)
You have to first change this in reverse order.
ab.setTitle("Select a group");
ListView lvprojlist=(ListView) v1.findViewById(R.id.projdisplaylist);
ab.setView(v1);
You have to set view after find id of your ListView.
Also don't make adplist variable globally. Make it static.
ArrayAdapter<String >adplist=new ArrayAdapter<String>(RegActivity.this, R.layout.list_item, R.id.rowtext, projlist);
Related
I have popupMenu and CheckBox. I need make write status CheckBox to boolean.
This code not working:
MenuItem fast_result;
boolean fast=false;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.FastResult:
fast_result = item.getSubMenu().getItem(R.id.FastResult);//This is 182 line
fast_result.setChecked(!fast_result.isChecked());
fast=fast_result.isChecked();
return true;
}
}
It is errors:
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.alexvsalex.HelpforMath.RootsActivity.onOptionsItemSelected(RootsActivity.java:182)
at android.app.Activity.onMenuItemSelected(Activity.java:2502)
at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:950)
at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:735)
at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:149)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:874)
at com.android.internal.view.menu.ListMenuPresenter.onItemClick(ListMenuPresenter.java:163)
at android.widget.AdapterView.performItemClick(AdapterView.java:292)
at android.widget.AbsListView.performItemClick(AbsListView.java:1058)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:2514)
at android.widget.AbsListView$1.run(AbsListView.java:3168)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
What to do?
The problem is solved:
case R.id.FastResult:
fast_result = item; //There was an error
fast_result.setChecked(!fast_result.isChecked());
fast=fast_result.isChecked();
return true;
im making a simple calories calculator and it gives me that error, i already reviewed the code and searched here for the solution but im not able to see why is not running.
I thought it was because i had not initialized the variable, so i did it and still got the same error, maybe is something with the spinners, im new on using spinners
here is the code:
public class CaloriesCalculator extends ActionBarActivity {
EditText etAge, etWeight, etHeight;
Button btnCalculate;
TextView tvResult;
Spinner spinnerGender, spinnerActivity;
String itemGender, itemActivity;
int Height=0;
int Weight=0;
int Age=0;;
double bmr=0.0;
double tdee=0.0;
String result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.caloriescalculator);
spinnerGender=(Spinner)findViewById(R.id.spinnerGender);
spinnerActivity=(Spinner)findViewById(R.id.spinnerActivity);
etAge=(EditText)findViewById(R.id.etAge);
etWeight=(EditText)findViewById(R.id.etWeight);
etHeight=(EditText)findViewById(R.id.etHeight);
tvResult=(TextView)findViewById(R.id.tvResult);
List<String> list = new ArrayList<String>();
list.add("Male");
list.add("Female");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, list );
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerGender.setAdapter(dataAdapter);
List<String> list2 = new ArrayList<String>();
list.add("Sedentary");
list.add("Lightly Active");
list.add("Moderalety Active");
list.add("Very Active");
list.add("Extremely Active");
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, list2 );
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerActivity.setAdapter(dataAdapter2);
btnCalculate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
spinnerGender.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
spinnerActivity.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
itemGender=String.valueOf(spinnerGender.getSelectedItem());
itemActivity=String.valueOf(spinnerActivity.getSelectedItem());
if(itemGender=="Male"){
Weight=Integer.parseInt(etWeight.getText().toString());
Height=Integer.parseInt(etHeight.getText().toString());
Age=Integer.parseInt(etAge.getText().toString());
if(itemActivity=="Sedentary"){
bmr=66+((13.7 * Weight)+(5*Height))-(6.8*Age);
tdee=bmr*1.2;
}
else if(itemActivity=="Lightly Active"){
bmr=66+((13.7 * Weight)+(5*Height))-(6.8*Age);
tdee=bmr*1.375;
}
else if(itemActivity=="Moderalety Active"){
bmr=66+((13.7 * Weight)+(5*Height))-(6.8*Age);
tdee=bmr*1.55;
}
else if(itemActivity=="Very Active"){
bmr=66+((13.7 * Weight)+(5*Height))-(6.8*Age);
tdee=bmr*1.725;
}
else if(itemActivity=="Extremely Active"){
bmr=66+((13.7 * Weight)+(5*Height))-(6.8*Age);
tdee=bmr*1.9;
}
}
else if(itemGender=="Female") {
Weight=Integer.parseInt(etWeight.getText().toString());
Height=Integer.parseInt(etHeight.getText().toString());
Age=Integer.parseInt(etAge.getText().toString());
if(itemActivity=="Sedentary"){
bmr=655+((9.6*Weight)+(1.8*Height))-(4.7*Age);
tdee=bmr*1.2;
}
else if(itemActivity=="Lightly Active"){
bmr=655+((9.6*Weight)+(1.8*Height))-(4.7*Age);
tdee=bmr*1.375;
}
else if(itemActivity=="Moderalety Active"){
bmr=655+((9.6*Weight)+(1.8*Height))-(4.7*Age);
tdee=bmr*1.55;
}
else if(itemActivity=="Very Active"){
bmr=655+((9.6*Weight)+(1.8*Height))-(4.7*Age);
tdee=bmr*1.725;
}
else if(itemActivity=="Extremely Active"){
bmr=655+((9.6*Weight)+(1.8*Height))-(4.7*Age);
tdee=bmr*1.9;
}
}
result=Double.toString(tdee);
tvResult.setText(result);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
logcat:
11-28 17:20:05.501: E/AndroidRuntime(1455): FATAL EXCEPTION: main
11-28 17:20:05.501: E/AndroidRuntime(1455): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.calculadoracalorias/com.app.calculadoracalorias.CaloriesCalculator}: java.lang.NullPointerException
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.os.Handler.dispatchMessage(Handler.java:99)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.os.Looper.loop(Looper.java:137)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-28 17:20:05.501: E/AndroidRuntime(1455): at java.lang.reflect.Method.invokeNative(Native Method)
11-28 17:20:05.501: E/AndroidRuntime(1455): at java.lang.reflect.Method.invoke(Method.java:525)
11-28 17:20:05.501: E/AndroidRuntime(1455): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-28 17:20:05.501: E/AndroidRuntime(1455): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-28 17:20:05.501: E/AndroidRuntime(1455): at dalvik.system.NativeStart.main(Native Method)
11-28 17:20:05.501: E/AndroidRuntime(1455): Caused by: java.lang.NullPointerException
11-28 17:20:05.501: E/AndroidRuntime(1455): at com.app.calculadoracalorias.CaloriesCalculator.onCreate(CaloriesCalculator.java:67)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.Activity.performCreate(Activity.java:5133)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-28 17:20:05.501: E/AndroidRuntime(1455): ... 11 more
11-28 17:24:42.341: D/AndroidRuntime(1507): Shutting down VM
11-28 17:24:42.341: W/dalvikvm(1507): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-28 17:24:42.371: E/AndroidRuntime(1507): FATAL EXCEPTION: main
11-28 17:24:42.371: E/AndroidRuntime(1507): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.calculadoracalorias/com.app.calculadoracalorias.CaloriesCalculator}: java.lang.NullPointerException
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.os.Handler.dispatchMessage(Handler.java:99)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.os.Looper.loop(Looper.java:137)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-28 17:24:42.371: E/AndroidRuntime(1507): at java.lang.reflect.Method.invokeNative(Native Method)
11-28 17:24:42.371: E/AndroidRuntime(1507): at java.lang.reflect.Method.invoke(Method.java:525)
11-28 17:24:42.371: E/AndroidRuntime(1507): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-28 17:24:42.371: E/AndroidRuntime(1507): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-28 17:24:42.371: E/AndroidRuntime(1507): at dalvik.system.NativeStart.main(Native Method)
11-28 17:24:42.371: E/AndroidRuntime(1507): Caused by: java.lang.NullPointerException
11-28 17:24:42.371: E/AndroidRuntime(1507): at com.app.calculadoracalorias.CaloriesCalculator.onCreate(CaloriesCalculator.java:70)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.Activity.performCreate(Activity.java:5133)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-28 17:24:42.371: E/AndroidRuntime(1507): ... 11 more
Yout btnCalculate is null, you should initialize before doing the onclickListener:
btnCalculate = (Button)findViewById(R.id.btnCalculate); //your id
Also note that you are initializing the dataAdapter2 but actually you are using dataAdapert, and list2 dont have any elements, because you declare it but u are filling always list1
This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 9 years ago.
I have a problem.
I want to know where did the android.os.NetworkOnMainThreadException and
java.lang.reflect.InvocationTargetException Exception come from !
Please, I'm new to Android and I need your help guys!
My LogCat:
12-19 13:00:27.049: E/AndroidRuntime(1170): FATAL EXCEPTION: main
12-19 13:00:27.049: E/AndroidRuntime(1170): java.lang.IllegalStateException: Could not execute method of the activity
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.view.View$1.onClick(View.java:3633)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.view.View.performClick(View.java:4240)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.view.View$PerformClick.run(View.java:17721)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.os.Handler.handleCallback(Handler.java:730)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.os.Handler.dispatchMessage(Handler.java:92)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.os.Looper.loop(Looper.java:137)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.app.ActivityThread.main(ActivityThread.java:5103)
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.lang.reflect.Method.invokeNative(Native Method)
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.lang.reflect.Method.invoke(Method.java:525)
12-19 13:00:27.049: E/AndroidRuntime(1170): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-19 13:00:27.049: E/AndroidRuntime(1170): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-19 13:00:27.049: E/AndroidRuntime(1170): at dalvik.system.NativeStart.main(Native Method)
12-19 13:00:27.049: E/AndroidRuntime(1170): Caused by: java.lang.reflect.InvocationTargetException
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.lang.reflect.Method.invokeNative(Native Method)
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.lang.reflect.Method.invoke(Method.java:525)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.view.View$1.onClick(View.java:3628)
12-19 13:00:27.049: E/AndroidRuntime(1170): ... 11 more
12-19 13:00:27.049: E/AndroidRuntime(1170): Caused by: android.os.NetworkOnMainThreadException
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
12-19 13:00:27.049: E/AndroidRuntime(1170): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
12-19 13:00:27.049: E/AndroidRuntime(1170): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
12-19 13:00:27.049: E/AndroidRuntime(1170): at libcore.io.IoBridge.connect(IoBridge.java:112)
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.net.Socket.connect(Socket.java:842)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
12-19 13:00:27.049: E/AndroidRuntime(1170): at com.ensem.sehaty.MainActivity.recupererListMed(MainActivity.java:58)
12-19 13:00:27.049: E/AndroidRuntime(1170): ... 14 more
12-19 13:05:27.366: I/Process(1170): Sending signal. PID: 1170 SIG: 9
MainActivity.java
public class MainActivity extends Activity {
Button btnRecupListMed = null;
ListView listeMed = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnRecupListMed = (Button) findViewById(R.id.btnListMed);
listeMed = (ListView) findViewById(R.id.listMed);
}
public void recupererListMed(View v){
BufferedReader br = null;
StringBuffer sb = new StringBuffer("");
try {
HttpClient client = new DefaultHttpClient();
HttpProtocolParams.setUseExpectContinue(client.getParams(), false);
HttpGet get = new HttpGet();
URI uri = new URI("http://105.153.20.252");
get.setURI(uri);
HttpResponse reponse = client.execute(get);
InputStream is = reponse.getEntity().getContent();
br = new BufferedReader(new InputStreamReader(is));
String str = br.readLine();
while(str != null){
sb.append(str);
sb.append("\n");
str = br.readLine();
}
} catch (URISyntaxException e) {
e.printStackTrace();
System.out.println("Erreur 1");
} catch (ClientProtocolException e) {
e.printStackTrace();
System.out.println("Erreur 2");
} catch (IOException e) {
e.printStackTrace();
System.out.println("Erreur 3");
}
try {
//ArrayList<HashMap<String, String>> medecins = new ArrayList<HashMap<String, String>>();
JSONArray js = new JSONArray(sb.toString());
List<String> listM = new ArrayList<String>();
for(int i=0; i<js.length(); i++){
JSONObject jsObj = js.getJSONObject(i);
String nom = jsObj.getString("NOMMED");
listM.add(nom);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, R.id.listMed, listM);
listeMed.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
System.out.println("Erreur 4");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
activity_main.xml
<TextView
android:text="#string/lbl_sehaty"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="#+id/btnListMed"
android:text="#string/lbl_btn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:onClick="recupererListMed"
/>
<ListView
android:id="#+id/listMed"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_marginTop="60dp">
</ListView>
And my Manifest contains the following permission
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Thanks.
This error comes when you try to make a server call on UI thread.
You should create an AsyncTask and put your server call in it.
And on click of button call execute on the object of asynctask.
Ex:
public class ServiceTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
BufferedReader br = null;
StringBuffer sb = new StringBuffer("");
try {
HttpClient client = new DefaultHttpClient();
HttpProtocolParams.setUseExpectContinue(client.getParams(), false);
HttpGet get = new HttpGet();
URI uri = new URI("http://105.153.20.252");
get.setURI(uri);
HttpResponse reponse = client.execute(get);
InputStream is = reponse.getEntity().getContent();
br = new BufferedReader(new InputStreamReader(is));
String str = br.readLine();
while(str != null){
sb.append(str);
sb.append("\n");
str = br.readLine();
}
} catch (URISyntaxException e) {
e.printStackTrace();
System.out.println("Erreur 1");
} catch (ClientProtocolException e) {
e.printStackTrace();
System.out.println("Erreur 2");
} catch (IOException e) {
e.printStackTrace();
System.out.println("Erreur 3");
}
return sb;
}
#Override
protected void onPostExecute(String result) {
try {
//ArrayList<HashMap<String, String>> medecins = new ArrayList<HashMap<String, String>>();
JSONArray js = new JSONArray(result.toString());
List<String> listM = new ArrayList<String>();
for(int i=0; i<js.length(); i++){
JSONObject jsObj = js.getJSONObject(i);
String nom = jsObj.getString("NOMMED");
listM.add(nom);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, R.id.listMed, listM);
listeMed.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
System.out.println("Erreur 4");
}
}
}
And inside your onClick event:
public void recupererListMed(View v){
new ServiceTask().execute();
}
This will execute doInBackground method on a different thread and once result is fetched onPostExecute is called on UI thread.
i have made 2 classes YehActivity.java and h.java. On running the application i am getting an error ,Application has stopped unexpectedly.Here is the code
public class YehActivity extends Activity {
public static final int r=1;
Button b;
TextView tv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(YehActivity.this,he.class);
//startActivity(i);
startActivityForResult(i, r);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode==r && resultCode==RESULT_OK){
String h=data.getStringExtra("a");
tv.setText(h);
}
}
}
where to check for null.
this is the second file
public class he extends Activity{
Button b;
EditText et;
Intent i=getIntent();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.h);
b=(Button) findViewById(R.id.button12);
et=(EditText) findViewById(R.id.editText1);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String value=et.getText().toString().trim();
i.putExtra("a", value);
he.this.setResult(RESULT_OK, i);
finish();
}
});
}
}
and the log file is
02-11 23:31:46.408: I/Process(302): Sending signal. PID: 302 SIG: 9
02-11 23:45:04.778: D/AndroidRuntime(357): Shutting down VM
02-11 23:45:04.778: W/dalvikvm(357): threadid=1: thread exiting with uncaught exception (group=0x40015560)
02-11 23:45:04.798: E/AndroidRuntime(357): FATAL EXCEPTION: main
02-11 23:45:04.798: E/AndroidRuntime(357): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ye/com.ye.YehActivity}: java.lang.NullPointerException
02-11 23:45:04.798: E/AndroidRuntime(357): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
02-11 23:45:04.798: E/AndroidRuntime(357): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
02-11 23:45:04.798: E/AndroidRuntime(357): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
02-11 23:45:04.798: E/AndroidRuntime(357): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
02-11 23:45:04.798: E/AndroidRuntime(357): at android.os.Handler.dispatchMessage(Handler.java:99)
02-11 23:45:04.798: E/AndroidRuntime(357): at android.os.Looper.loop(Looper.java:123)
02-11 23:45:04.798: E/AndroidRuntime(357): at android.app.ActivityThread.main(ActivityThread.java:3683)
02-11 23:45:04.798: E/AndroidRuntime(357): at java.lang.reflect.Method.invokeNative(Native Method)
02-11 23:45:04.798: E/AndroidRuntime(357): at java.lang.reflect.Method.invoke(Method.java:507)
02-11 23:45:04.798: E/AndroidRuntime(357): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-11 23:45:04.798: E/AndroidRuntime(357): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-11 23:45:04.798: E/AndroidRuntime(357): at dalvik.system.NativeStart.main(Native Method)
02-11 23:45:04.798: E/AndroidRuntime(357): Caused by: java.lang.NullPointerException
02-11 23:45:04.798: E/AndroidRuntime(357): at com.ye.YehActivity.onCreate(YehActivity.java:23)
02-11 23:45:04.798: E/AndroidRuntime(357): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-11 23:45:04.798: E/AndroidRuntime(357): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
02-11 23:45:04.798: E/AndroidRuntime(357): ... 11 more
02-11 23:45:11.158: I/Process(357): Sending signal. PID: 357 SIG: 9
02-11 23:45:22.708: D/AndroidRuntime(374): Shutting down VM
02-11 23:45:22.708: W/dalvikvm(374): threadid=1: thread exiting with uncaught exception (group=0x40015560)
02-11 23:45:22.728: E/AndroidRuntime(374): FATAL EXCEPTION: main
02-11 23:45:22.728: E/AndroidRuntime(374): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ye/com.ye.YehActivity}: java.lang.NullPointerException
02-11 23:45:22.728: E/AndroidRuntime(374): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
02-11 23:45:22.728: E/AndroidRuntime(374): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
02-11 23:45:22.728: E/AndroidRuntime(374): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
02-11 23:45:22.728: E/AndroidRuntime(374): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
02-11 23:45:22.728: E/AndroidRuntime(374): at android.os.Handler.dispatchMessage(Handler.java:99)
02-11 23:45:22.728: E/AndroidRuntime(374): at android.os.Looper.loop(Looper.java:123)
02-11 23:45:22.728: E/AndroidRuntime(374): at android.app.ActivityThread.main(ActivityThread.java:3683)
02-11 23:45:22.728: E/AndroidRuntime(374): at java.lang.reflect.Method.invokeNative(Native Method)
02-11 23:45:22.728: E/AndroidRuntime(374): at java.lang.reflect.Method.invoke(Method.java:507)
02-11 23:45:22.728: E/AndroidRuntime(374): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-11 23:45:22.728: E/AndroidRuntime(374): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-11 23:45:22.728: E/AndroidRuntime(374): at dalvik.system.NativeStart.main(Native Method)
02-11 23:45:22.728: E/AndroidRuntime(374): Caused by: java.lang.NullPointerException
02-11 23:45:22.728: E/AndroidRuntime(374): at com.ye.YehActivity.onCreate(YehActivity.java:23)
02-11 23:45:22.728: E/AndroidRuntime(374): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-11 23:45:22.728: E/AndroidRuntime(374): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
02-11 23:45:22.728: E/AndroidRuntime(374): ... 11 more
02-11 23:45:25.497: I/Process(374): Sending signal. PID: 374 SIG: 9
In your
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(YehActivity.this,he.class);
//startActivity(i);
startActivityForResult(i, r);
}
});
}
onCreate() method you attempt to use b, but you never initialize it (I'm assuming its declared as a global variable). This means that you will run into a NullPointerException when you try to call setOnClickListener().
In your code in OnCreate() you have to declare b as button and then apply listener to that.
b=(Button) findViewById(R.id.button12);
Also check your data is null or not. If it is null than handle it properly.
Then your code runs fine.
I'm trying to start a service, but always getting NPE. What could I be doing wrong?
Even the onServiceConnected() method does not get called, why ever?
#Override
protected void onCreate(Bundle savedInstanceState) {
mServiceIntent = new Intent(this, MyService.class);
bindService(mServiceIntent, mConnection, Context.BIND_AUTO_CREATE);
//other stuff
}
usage:
private okButton(View v) {
startService(mServiceIntent);
}
result: NullPointerException!
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
Log.v("service", "gets never executed!");
mDownloadService = ((LocalBinder<MyService>) service).getService();
}
#Override
public void onServiceDisconnected(ComponentName className) {
}
};
}
public class LocalBinder<S> extends Binder {
private String TAG = "LocalBinder";
private WeakReference<S> mService;
public LocalBinder(S service){
mService = new WeakReference<S>(service);
}
public S getService() {
return mService.get();
}
}
Of course I also have the service in manifest:
<service android:enabled="true" android:name=".service.MyService" />
Logcat:
06-06 23:48:20.411: W/dalvikvm(592): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
06-06 23:48:20.461: E/AndroidRuntime(592): FATAL EXCEPTION: main
06-06 23:48:20.461: E/AndroidRuntime(592): java.lang.RuntimeException: Unable to start activity ComponentInfo{MyActivity}: java.lang.NullPointerException
06-06 23:48:20.461: E/AndroidRuntime(592): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
06-06 23:48:20.461: E/AndroidRuntime(592): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
06-06 23:48:20.461: E/AndroidRuntime(592): at android.app.ActivityThread.access$600(ActivityThread.java:123)
06-06 23:48:20.461: E/AndroidRuntime(592): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
06-06 23:48:20.461: E/AndroidRuntime(592): at android.os.Handler.dispatchMessage(Handler.java:99)
06-06 23:48:20.461: E/AndroidRuntime(592): at android.os.Looper.loop(Looper.java:137)
06-06 23:48:20.461: E/AndroidRuntime(592): at android.app.ActivityThread.main(ActivityThread.java:4424)
06-06 23:48:20.461: E/AndroidRuntime(592): at java.lang.reflect.Method.invokeNative(Native Method)
06-06 23:48:20.461: E/AndroidRuntime(592): at java.lang.reflect.Method.invoke(Method.java:511)
06-06 23:48:20.461: E/AndroidRuntime(592): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
06-06 23:48:20.461: E/AndroidRuntime(592): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
06-06 23:48:20.461: E/AndroidRuntime(592): at dalvik.system.NativeStart.main(Native Method)
06-06 23:48:20.461: E/AndroidRuntime(592): Caused by: java.lang.NullPointerException
06-06 23:48:20.461: E/AndroidRuntime(592): at MyActivity.okButton(MyActivity.java:217)
06-06 23:48:20.461: E/AndroidRuntime(592): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1939)
06-06 23:48:20.461: E/AndroidRuntime(592): ... 11 more
The intent seems to be ok:
Log.v("service", String.valueOf(mServiceIntent == null)); //false
Your stack trace clearly shows the NullPointerException happening in okButton(), and according to the code you posted, the only line in that function is
startService(mServiceIntent);
So clearly mServiceIntent is null at this point, despite being set in onCreate().
Do you have any other lines where you set mServiceIntent?
Or do you have a constructor in which you call okButton()? A constructor is the only thing I can think of that would run before onCreate(). That would also explain why onServiceConnected() is never run despite the call to bindService() in onCreate().
This code is not proper Java syntax, as the method definition has no return type :
private okButton(View v) {
startService(mServiceIntent);
}
You need something like:
private void okButton(View v) {
startService(mServiceIntent);
}
It looks to me from the stack trace that the okButton() method is being called during the creation of the MyActivity instance before the onCreate() method is called and of course at that time mService will be null.
Post more code or correct the code you've posted so that it actually matches what you are using.