I'm trying to add some values to my database from my android application through JSON.
I have used the below code previously with eclipse and worked perfectly, now im trying it using android studio and it isn't working I don't know why!
code:
public class Main2Activity extends AppCompatActivity {
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText ID;
EditText fname;
EditText lname;
EditText phone;
Button addbtn;
// url to create new product
private static String url_create_product = "http://www.lamia.byethost18.com/add_info.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
String H,Q,C,Ls;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
ID = (EditText) findViewById(R.id.ID);
lname = (EditText) findViewById(R.id.lname);
fname = (EditText) findViewById(R.id.fname);
phone = (EditText) findViewById(R.id.phone);
H = ID.getText().toString();
Q = lname.getText().toString();
C = fname.getText().toString();
Ls = phone.getText().toString();
addbtn = (Button) findViewById(R.id.addbtn);
addbtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
new CreateNewProduct().execute();
}
});
}
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Main2Activity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("ID", H));
params.add(new BasicNameValuePair("lname", Q));
params.add(new BasicNameValuePair("fname", C));
params.add(new BasicNameValuePair("phone", Ls));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
// Intent i = new Intent(getApplicationContext(), AdminExercise.class);
// startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
I got this error:
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/JSON Parser: Error parsing data org.json.JSONException: Value <html><body><script of type java.lang.String cannot be converted to JSONObject
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #4
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: Process: com.example.hatim.maps, PID: 1934
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: java.lang.RuntimeException: An error occurred while executing doInBackground()
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: at android.os.AsyncTask$3.done(AsyncTask.java:309)
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:242)
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: at java.lang.Thread.run(Thread.java:818)
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: at com.example.hatim.maps.Main2Activity$CreateNewProduct.doInBackground(Main2Activity.java:113)
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: at com.example.hatim.maps.Main2Activity$CreateNewProduct.doInBackground(Main2Activity.java:77)
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: at android.os.AsyncTask$2.call(AsyncTask.java:295)
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
04-14 21:08:36.214 1934-1980/com.example.hatim.maps E/AndroidRuntime: at java.lang.Thread.run(Thread.java:818)
I don't get what is the error?
can someone help please? thank you!
It seems that your request is not receiving a JSON, may be is an HTML error because the value received starts with html format:
E/JSON Parser: Error parsing data org.json.JSONException: Value <html><body><script of type java.lang.String cannot be converted to JSONObject
I created a button and assigned it 1 by doing
remove.setId(0 + count);
Then I tried to put that button in my onCreate bundle to use it
Button remove = (Button)findViewById(1);
remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
When I create the button remove in my oncreate it runs but as soon as I add my onclick listener I dont get any errors but when I run it it force closes
Log
12-12 13:42:06.172: D/AndroidRuntime(19502): Shutting down VM
12-12 13:42:06.172: W/dalvikvm(19502): threadid=1: thread exiting with uncaught exception (group=0x416bbd40)
12-12 13:42:06.178: E/AndroidRuntime(19502): FATAL EXCEPTION: main
12-12 13:42:06.178: E/AndroidRuntime(19502): Process: com.th3ramr0d.armytrooptotask, PID: 19502
12-12 13:42:06.178: E/AndroidRuntime(19502): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.th3ramr0d.armytrooptotask/com.th3ramr0d.armytrooptotask.MainActivity}: java.lang.NullPointerException
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread.access$800(ActivityThread.java:139)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.os.Handler.dispatchMessage(Handler.java:102)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.os.Looper.loop(Looper.java:136)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread.main(ActivityThread.java:5102)
12-12 13:42:06.178: E/AndroidRuntime(19502): at java.lang.reflect.Method.invokeNative(Native Method)
12-12 13:42:06.178: E/AndroidRuntime(19502): at java.lang.reflect.Method.invoke(Method.java:515)
12-12 13:42:06.178: E/AndroidRuntime(19502): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
12-12 13:42:06.178: E/AndroidRuntime(19502): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
12-12 13:42:06.178: E/AndroidRuntime(19502): at dalvik.system.NativeStart.main(Native Method)
12-12 13:42:06.178: E/AndroidRuntime(19502): Caused by: java.lang.NullPointerException
12-12 13:42:06.178: E/AndroidRuntime(19502): at com.th3ramr0d.armytrooptotask.MainActivity.onCreate(MainActivity.java:45)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.Activity.performCreate(Activity.java:5248)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2173)
12-12 13:42:06.178: E/AndroidRuntime(19502): ... 11 more
Here is my full file
package com.th3ramr0d.armytrooptotask;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
public class MainActivity extends Activity {
public int count = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button addTroopBtn = (Button) findViewById(R.id.addTroop);
addTroopBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(count <= 5)
{
inputName(v);
}
else
{
}
}
});
Button remove = (Button)findViewById(1);
remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
}
public void inputName(final View v){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
//alert.setTitle("Enter Name and Rank");
alert.setMessage("Please Enter A Name");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Editable name = input.getText();
addTroop(name);
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
}
public void addTroop(Editable name){
LinearLayout mainPage = (LinearLayout) findViewById(R.id.manageTroopsMain);
if (count <= 5)
{
//CREATE NEW LINEAR LAYOUT
LinearLayout addTroopLayout = new LinearLayout(this);
//CREATE LAYOUT PARAMS FOR LAYOUT
LinearLayout.LayoutParams newLayout = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
newLayout.bottomMargin = 10;
//STYLE NEW LINEAR LAYOUT
addTroopLayout.setTag("addTroopLayout" + count);
addTroopLayout.setLayoutParams(newLayout);
addTroopLayout.setOrientation(LinearLayout.HORIZONTAL);
//CREATE NEW BUTTONS
Button newTroop = new Button(this);
Button remove = new Button(this);
Button change = new Button(this);
//CREATE LAYOUT PARAMS FOR BUTTONS
LinearLayout.LayoutParams newTroopParam = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 20f);
LinearLayout.LayoutParams rmvBtnParam = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, .5f);
LinearLayout.LayoutParams chngNameParam = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, .5f);
//STYLE NEW BUTTONS
newTroop.setText(name);
newTroop.setGravity(Gravity.LEFT|Gravity.CENTER_VERTICAL);
newTroop.setLayoutParams(newTroopParam);
remove.setId(0 + count);
remove.setText("-");
remove.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
remove.setLayoutParams(rmvBtnParam);
change.setText("...");
change.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
change.setLayoutParams(chngNameParam);
//ADD VIEWS TO NEW LAYOUT
addTroopLayout.addView(newTroop);
addTroopLayout.addView(remove);
addTroopLayout.addView(change);
//ADD NEW LAYOUT TO mainPage LAYOUT
mainPage.addView(addTroopLayout);
//Increment Counter
count++;
}
}
}
This is your problem:
Button remove = (Button)findViewById(1);
This should be something like this:
Button remove = (Button)findViewById(R.id.buttonRemove); // that should be a long int
The crash is likely happening from this line:
Button remove = (Button)findViewById(1);
You'll need to provide a valid ID for a Button within your inflated layout. A value of 1 is not meaningful.
hi guys i have a problem. when i run my app, one activity crash after i press the buttons x times. sometimes it works, sometimes not. please help. don't know what to do.strong text
08-08 09:19:57.087: E/AndroidRuntime(2772): FATAL EXCEPTION: main
08-08 09:19:57.087: E/AndroidRuntime(2772): Process: org.nolodigas, PID: 2772
08-08 09:19:57.087: E/AndroidRuntime(2772): java.lang.IllegalStateException: Could not execute method of the activity
08-08 09:19:57.087: E/AndroidRuntime(2772): at android.view.View$1.onClick(View.java:3823)
08-08 09:19:57.087: E/AndroidRuntime(2772): at android.view.View.performClick(View.java:4438)
08-08 09:19:57.087: E/AndroidRuntime(2772): at android.view.View$PerformClick.run(View.java:18422)
08-08 09:19:57.087: E/AndroidRuntime(2772): at android.os.Handler.handleCallback(Handler.java:733)
08-08 09:19:57.087: E/AndroidRuntime(2772): at android.os.Handler.dispatchMessage(Handler.java:95)
08-08 09:19:57.087: E/AndroidRuntime(2772): at android.os.Looper.loop(Looper.java:136)
08-08 09:19:57.087: E/AndroidRuntime(2772): at android.app.ActivityThread.main(ActivityThread.java:5017)
08-08 09:19:57.087: E/AndroidRuntime(2772): at java.lang.reflect.Method.invokeNative(Native Method)
08-08 09:19:57.087: E/AndroidRuntime(2772): at java.lang.reflect.Method.invoke(Method.java:515)
08-08 09:19:57.087: E/AndroidRuntime(2772): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-08 09:19:57.087: E/AndroidRuntime(2772): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-08 09:19:57.087: E/AndroidRuntime(2772): at dalvik.system.NativeStart.main(Native Method)
08-08 09:19:57.087: E/AndroidRuntime(2772): Caused by: java.lang.reflect.InvocationTargetException
08-08 09:19:57.087: E/AndroidRuntime(2772): at java.lang.reflect.Method.invokeNative(Native Method)
08-08 09:19:57.087: E/AndroidRuntime(2772): at java.lang.reflect.Method.invoke(Method.java:515)
08-08 09:19:57.087: E/AndroidRuntime(2772): at android.view.View$1.onClick(View.java:3818)
08-08 09:19:57.087: E/AndroidRuntime(2772): ... 11 more
08-08 09:19:57.087: E/AndroidRuntime(2772): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=121; index=123
08-08 09:19:57.087: E/AndroidRuntime(2772): at org.nolodigas.Jugar.okButton(Jugar.java:104)
08-08 09:19:57.087: E/AndroidRuntime(2772): ... 14 more
there is my logcat. i can't find the error . here is my java code
public class Jugar extends Activity implements ViewSwitcher.ViewFactory,
View.OnClickListener {
private TextSwitcher mSwitcher;
TextView textViewTime;
ImageView img;
int cont=0;
private int mCounter = 0;
private int[] a = {
R.drawable.casa,R.drawable.cantar,R.drawable.agua,R.drawable.anciana,R.drawable.arbol,R.drawable.mochila,R.drawable.auto,R.drawable.azucar,R.drawable.libro,R.drawable.empresa,R.drawable.control,R.drawable.computadora,R.drawable.boca,
R.drawable.boliche,R.drawable.campo,R.drawable.cantar,R.drawable.cargador,R.drawable.casa,R.drawable.casamiento,R.drawable.cerveza,R.drawable.cocina,R.drawable.concierto,R.drawable.control,R.drawable.cuaderno,R.drawable.cuerpo,R.drawable.deporte,R.drawable.dj,
R.drawable.doctor,R.drawable.droga,R.drawable.edificio,R.drawable.empresa,R.drawable.escritor,R.drawable.famoso,R.drawable.ganso,R.drawable.gato,R.drawable.gente,R.drawable.ginobili,R.drawable.grande,R.drawable.hospital,R.drawable.hotel,
R.drawable.huerfano,R.drawable.ingeniero,R.drawable.jugo,R.drawable.libreria,R.drawable.libro,R.drawable.mesa,R.drawable.mochila,R.drawable.museo,R.drawable.musica,R.drawable.naranja,R.drawable.nieve,R.drawable.ovni,R.drawable.paris,
R.drawable.pasto,R.drawable.pelo,R.drawable.pelota,R.drawable.pendrive,R.drawable.periodista,R.drawable.perro,R.drawable.piramide,R.drawable.pistola,R.drawable.planeta,R.drawable.playa,R.drawable.sirena,R.drawable.abogado,R.drawable.esqui,R.drawable.funda,R.drawable.disco,
R.drawable.pornografia,R.drawable.profesor,R.drawable.puerta,R.drawable.radio,R.drawable.rio,R.drawable.roma,R.drawable.ropa,R.drawable.sillon,R.drawable.superheroe,R.drawable.taza,R.drawable.luz,R.drawable.lapiz,R.drawable.ron,R.drawable.fernet,R.drawable.bariloche,R.drawable.garage,R.drawable.alarma,
R.drawable.tela,R.drawable.televisor,R.drawable.unia,R.drawable.ventana,R.drawable.ventilador,R.drawable.viajar,R.drawable.zapatillas,R.drawable.pelea,R.drawable.panda,R.drawable.cable,R.drawable.tinelli,R.drawable.manzana,R.drawable.ftutilla,R.drawable.leche,R.drawable.fotocopia,
R.drawable.mono,R.drawable.piano,R.drawable.guitarra,R.drawable.bateria,R.drawable.camara,R.drawable.bombon,R.drawable.tren,R.drawable.pintura,R.drawable.aldea,R.drawable.grito,R.drawable.bandera,R.drawable.messi,R.drawable.aguero,R.drawable.legrand,R.drawable.zuckerberg,R.drawable.billetera,R.drawable.guepardo,R.drawable.elefante,R.drawable.calle,R.drawable.gimnasio,R.drawable.argentina,
};
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.jugar);
mSwitcher = (TextSwitcher) findViewById(R.id.switcher);
mSwitcher.setFactory(this);
textViewTime = (TextView) findViewById(R.id.texto1);
textViewTime.setText("01:00");
Button nextButton = (Button) findViewById(R.id.next);
nextButton.setOnClickListener(this);
updateCounter();
}
private void updateCounter() {
mSwitcher.setText(String.valueOf(mCounter));
}
public View makeView() {
TextView t = new TextView(this);
t.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
t.setTextSize(36);
return t;
}
protected void setOrientation() {
int current = getRequestedOrientation();
// only switch the orientation if not in portrait
if ( current != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT ) {
setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
public void lanzarJugar(View v) {
}
#Override
public void onClick(View v) {
mCounter=0;
mSwitcher.setText(String.valueOf(mCounter));
final CounterClass timer = new CounterClass(60000, 1000);
timer.start();
ImageView img= (ImageView) findViewById(R.id.imageView1);
int rando = (int) (Math.random() * 125);
Drawable d = getResources().getDrawable(a[rando]);
img.setImageDrawable(d);
}
public void noButton(View v){
ImageView img= (ImageView) findViewById(R.id.imageView1);
int rando = (int) (Math.random() * 125);
Drawable d = getResources().getDrawable(a[rando]);
img.setImageDrawable(d);
}
public void okButton(View v) {
ImageView img= (ImageView) findViewById(R.id.imageView1);
int rando = (int) (Math.random() * 125);
Drawable d = getResources().getDrawable(a[rando]);
img.setImageDrawable(d);
mCounter++;
updateCounter();
cont++;
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint({ "NewApi", "DefaultLocale" })
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// TODO Auto-generated constructor stub
}
#SuppressLint("NewApi")
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
long millis = millisUntilFinished;
String ms = String.format("%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
System.out.println(ms);
textViewTime.setText(ms);
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
textViewTime.setText("Tiempo!");
}
}
}
In the code line below, you are generating a random number and picking an Resource Integer. But the index you are trying to get from array doesn't exist. So you are getting IndexOutOfBounds exception.
int rando = (int) (Math.random() * 125);
Drawable d = getResources().getDrawable(a[rando]);
Error is in okButton method here:
int rando = (int) (Math.random() * 125);
Drawable d = getResources().getDrawable(a[rando]);
rando is returning a value out bounds of a array.
Your array contains only 121 elements. Hence, whenever the random number generated is within 0-120 range, the app functions properly. But whenever the number falls between 121-124, it crashes due to IndexOutOfBounds exception. Either add more items to the array or use the following code:
int rando = (int) (Math.random() * 121);
Drawable d = getResources().getDrawable(a[rando]);
I have spinner in Activity and edittext's. When i run the app I'm getting warning of nullPointerException.I dosen't retrieve the SQLite data in edit text in onCreate().Can someone help me.
Here is my code.
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.delete_entry);
databaseHelper = new DatabaseHelper(this);
databaseHelper.onOpen(db);
spinner_searchByEmpName = (Spinner)findViewById(R.id.searchByEmpName);
loadSerachBYProject() ;
spinner_searchByEmpName.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
selectedEmployeeName = spinner_searchByEmpName.getSelectedItem().toString().trim();
System.out.println("selectedProjectName " + selectedEmployeeName);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
etEmpName=(EditText)findViewById(R.id.Delete_editText_StaffEmployee_Name);
etDepartment=(EditText)findViewById(R.id.Delete_editText_Department);
etDesignation=(EditText)findViewById(R.id.Delete_editText_Designation);
try {
Cursor cursor = db.rawQuery("SELECT staff_employee_id, staff_emp_name, department, designation FROM employee_details WHERE staff_emp_name = ?",
new String[] { "" + selectedEmployeeName });
etEmpName.setText(cursor.getString(cursor
.getColumnIndex("staff_emp_name")));
etDepartment.setText(cursor.getString(cursor
.getColumnIndex("department")));
etDesignation.setText(cursor.getString(cursor
.getColumnIndex("designation")));
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
private void loadSerachBYProject()
{
DatabaseHelper databaseHelper = new DatabaseHelper(getApplicationContext());
// Spinner Drop down elements
List<String> projectsName = databaseHelper.getAllEmployeeName();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, projectsName);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner_searchByEmpName.setAdapter(dataAdapter);
}
}
Thanks in Advance.
Here is My Log cat error info
06-26 18:08:09.073: W/System.err(601): java.lang.NullPointerException
06-26 18:08:09.083: W/System.err(601): at com.employee_review.Update_Entry.onCreate(Update_Entry.java:68)
06-26 18:08:09.083: W/System.err(601): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
06-26 18:08:09.083: W/System.err(601): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
06-26 18:08:09.083: W/System.err(601): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
06-26 18:08:09.092: W/System.err(601): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
06-26 18:08:09.092: W/System.err(601): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
06-26 18:08:09.103: W/System.err(601): at android.os.Handler.dispatchMessage(Handler.java:99)
06-26 18:08:09.103: W/System.err(601): at android.os.Looper.loop(Looper.java:123)
06-26 18:08:09.113: W/System.err(601): at android.app.ActivityThread.main(ActivityThread.java:3683)
06-26 18:08:09.123: W/System.err(601): at java.lang.reflect.Method.invokeNative(Native Method)
06-26 18:08:09.133: W/System.err(601): at java.lang.reflect.Method.invoke(Method.java:507)
06-26 18:08:09.133: W/System.err(601): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
06-26 18:08:09.133: W/System.err(601): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
06-26 18:08:09.133: W/System.err(601): at dalvik.system.NativeStart.main(Native Method)
Try this , i guess
if(cursor!=null){
etEmpName.setText(cursor.getString(cursor
.getColumnIndex("staff_emp_name")));
etDepartment.setText(cursor.getString(cursor
.getColumnIndex("department")));
etDesignation.setText(cursor.getString(cursor
.getColumnIndex("designation")));
}
db is never initialized. It must be initialized in onCreate(), as that's the first method that is run in an Activity. I see this:
databaseHelper = new DatabaseHelper(this);
databaseHelper.onOpen(db);
I'm guessing you really should have this:
databaseHelper = new DatabaseHelper(this);
db=databaseHelper.getReadableDatabase();
The code runs and my emails send, but anytime I check a box the subject is not altered because the method setSubject() is not called. Got it. Where I'm having trouble is where would I call/place this method so I can use the subject in my doInBackground() method. If I try calling setSubject() right before or anywhere in doInBackground I get an error for running concurrent tasks on the same thread. I tried calling setSubject() in a onPreExecute() block and still got the error. Anybody have any ideas? Here is the code and LogCat.
public class lastpage extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lastpage);
}
//method to verify email format using regex pattern
public boolean validateEmail(String email) {
Pattern pattern;
Matcher matcher;
//set variable to regex email pattern
final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(email);
if (matcher.matches()) {
return true;
}
return false;
}
public void sendEmails() {
AsyncTask<String, Void, Void> myTask = new AsyncTask<String, Void, Void>() {
private String sub = "Maintenance Request";
String s = "";
CheckBox main = (CheckBox) findViewById(R.id.checkBox1);
CheckBox kitchen = (CheckBox) findViewById(R.id.checkBox2);
CheckBox bathroom = (CheckBox) findViewById(R.id.checkBox3);
CheckBox other = (CheckBox) findViewById(R.id.checkBox4);
public String setSubject(String subject) {
sub = subject;
if (main.isChecked()) subject = subject + " - Main Room";
if (kitchen.isChecked()) subject = subject + " - Kitchen";
if (bathroom.isChecked()) subject = subject + " - Bathroom";
if (other.isChecked()) subject = subject + " - Other";
return subject;
}
s = setSubject(sub);
protected Void doInBackground(String... params) {
String host = "smtp.gmail.com";
String username = "user#gmail.com";
String password = "pwd";
Properties props = new Properties();
props.put("mail.smtp.ssl.enable", "true");
Session session = Session.getInstance(props);
session.setDebug(true);
EditText e = (EditText) findViewById(R.id.enterEmail);
EditText g = (EditText) findViewById(R.id.whichApt);
String f = e.toString().replace("\\s", "");
String to = "to#yahoo.com";
String manager = "manager#gmail.com";
String subject1 = "Maintenance Confirmation";
MimeMessage msg = new MimeMessage(session);
MimeMessage msg1 = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(username));
msg1.setFrom(new InternetAddress(username));
msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(to));
msg1.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(manager));
msg.setSubject(subject1);
msg1.setSubject(s);
msg.setText("Some really important stuff. Confirmed.");
msg1.setText("Really important stuff needs attention");
props.put("mail.smtps.auth", "true");
props.put("mail.smtp.quitwait", "false");
Transport t = session.getTransport("smtps");
try {
t.connect(host, username, password);
t.sendMessage(msg, msg.getAllRecipients());
t.sendMessage(msg1, msg1.getAllRecipients());
}
finally {
t.close();
} }
catch(Exception exc){
exc.printStackTrace();
}
return null;
}};
myTask.execute(); }
//method to run when button is clicked
public void buttonclick3(View v) {
//first extract text for EditText and convert to String
EditText e = (EditText) findViewById(R.id.enterEmail);
String email = e.getText().toString();
//run validateEmail on String and show alert if format is invalid
if (validateEmail(email) == false) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Please enter a valid Email address.");
builder.setTitle("Invalid Input!");
builder.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.show();
}
else {
sendEmails();
}
}
}
Here is the LogCat I get when I try calling setSubject() anywhere.
- 04-14 17:52:09.091: W/dalvikvm(1510): threadid=1: thread exiting with
uncaught exception (group=0x41bbaa08)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): FATAL EXCEPTION: main
- 04-14 17:52:09.101: E/AndroidRuntime(1510): java.lang.IllegalStateException: Could not execute method of the activity
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at android.view.View$1.onClick(View.java:3626)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at android.view.View.performClick(View.java:4231)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at android.view.View$PerformClick.run(View.java:17537)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at android.os.Handler.handleCallback(Handler.java:725)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at android.os.Handler.dispatchMessage(Handler.java:92)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at android.os.Looper.loop(Looper.java:158)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at android.app.ActivityThread.main(ActivityThread.java:5751)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at java.lang.reflect.Method.invokeNative(Native Method)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at java.lang.reflect.Method.invoke(Method.java:511)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1083)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:850)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at dalvik.system.NativeStart.main(Native Method)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): Caused by: java.lang.reflect.InvocationTargetException
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at java.lang.reflect.Method.invokeNative(Native Method)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at java.lang.reflect.Method.invoke(Method.java:511)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at android.view.View$1.onClick(View.java:3621)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): ... 11 more
- 04-14 17:52:09.101: E/AndroidRuntime(1510): Caused by: java.lang.NullPointerException
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at com.example.maintenanceapp.lastpage$1.setSubject(lastpage.java:81)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at com.example.maintenanceapp.lastpage$1.<init>(lastpage.java:87)
- 04-14 17:52:09.101: E/AndroidRuntime(1510): at com.example.maintenanceapp.lastpage.sendEmails(lastpage.java:72)
Don't try to find checkboxes on a different activity. Instead, send the information needed in the Intent used to start the next activity.