Problems with XmlPullParser code inside an AsyncTask (Activated By Button Click) - eclipse

SO I have a program that I have been working on for a while. However, I am stuck on method that uses XmlPullParser, the method is called getAllXml(). It is inside of the doInBackGround() method of an AsyncTask. The AsyncTask is a subclass of an Activity called FormActivity. When I run the code.
Here is what the code is supposed to do. After the user selects "CloverField" from a previous activity. An xml file called cloverfield_in.xml is called by setContentView(). The user then presses a button on this same xml file. Clicking this button executes the AsyncTask called MadLIbAsyncTask. Within this AsyncTask this are only two methods, the doInBackground() and the onPostExecute(). (I don't know if I need onPreExecute()...within which I would have have a progress bar....but without this method I figure the program shouldn't crash the way it does).
Within the doInBackground() method, I am calling the method called getAllXml(). This method uses XmlPullParser to search through the current xml (cloverfield_in.xml) and capture text from a single TextView. The code for getAllXml() is as follows.
public void getAllXml() throws XmlPullParserException, IOException{
Activity activity = this;
Resources res = activity.getResources();
XmlResourceParser xpp = res.getXml(R.layout.cloverfield_in);
int eventtype = xpp.getEventType();
while (eventtype != XmlPullParser.END_DOCUMENT){
if (eventtype == XmlPullParser.START_DOCUMENT){
}
else if (eventtype == XmlPullParser.START_TAG){
if (xpp.getName() == "TextView"){
while (eventtype != XmlPullParser.END_TAG){
if (eventtype == XmlPullParser.TEXT){
stringViews[0] = xpp.getText();
}else {}
eventtype = xpp.next();
}
}else {}
}
else if (eventtype == XmlPullParser.END_TAG){
}
else if (eventtype == XmlPullParser.TEXT){
}
eventtype = xpp.next();
}
}
When in the process of debugging, my program often returns a NullPointerException or a RunTimeException. I believe within this code is where the problem resides. I tested the AsyncTask without the existence of the getAllXml() method and everything works fine. Eventually the program is supposed to take the text gathered from the cloverfield_in.xml file and display it in a new file called cloverfield_out.xml.
For a complete review of everything, here is the entire code for FormActivity.class.
package com.muirconsult.mymadlibs;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Layout;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;
public class FormActivity extends Activity{
String [] textFields;
String Choice;
int thisLayout;
View thatLayout ;
String[] stringViews;
ViewGroup anskey;
Activity activity = this;
String test;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent objIntent = getIntent();
Choice = objIntent.getStringExtra("selection");
if (Choice.equals("Cloverfield")) {
setContentView(R.layout.cloverfield_in);
thisLayout = (R.layout.cloverfield_in);
thatLayout = (View)findViewById(R.layout.cloverfield_out);
}
if (Choice.equals("Fargo")) {
setContentView(R.layout.fargo_in);
}
if(Choice.equals("Ying Yang In This Thang (Ying Yang Twins)")){
setContentView(R.layout.ying_yang_twins_in_this_thang_in);
}
}
public void getAllXml() throws XmlPullParserException, IOException{
Activity activity = this;
Resources res = activity.getResources();
XmlResourceParser xpp = res.getXml(R.layout.cloverfield_in);
int eventtype = xpp.getEventType();
while (eventtype != XmlPullParser.END_DOCUMENT){
if (eventtype == XmlPullParser.START_DOCUMENT){
}
else if (eventtype == XmlPullParser.START_TAG){
if (xpp.getName() == "TextView"){
while (eventtype != XmlPullParser.END_TAG){
if (eventtype == XmlPullParser.TEXT){
stringViews[0] = xpp.getText();
}else {}
eventtype = xpp.next();
}
}else {}
}
else if (eventtype == XmlPullParser.END_TAG){
}
else if (eventtype == XmlPullParser.TEXT){
}
eventtype = xpp.next();
}
}
class MadLibAsyncTask extends AsyncTask<Void, Void, Void>{
String testString;
int thisLayout;
protected Void doInBackground(Void... params) {
try{
getAllXml();
}catch (XmlPullParserException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute (Void result){
String str = "let's go to the park";
String newstr;
setContentView(R.layout.cloverfield_out);
TextView outview = (TextView)findViewById(R.id.outview);
str = (String) outview.getText();
newstr = str.replaceFirst("film",stringViews[0]);
outview.setText(newstr);
}
}
public void onClick(View view) {
MadLibAsyncTask mad = new MadLibAsyncTask();
mad.execute();
}
}
Also, most importantly...the logcat looks as such:
08-10 23:04:50.064: W/dalvikvm(1415): threadid=1: thread exiting with uncaught exception >>> (group=0x40a71930)
08-10 23:04:50.145: E/AndroidRuntime(1415): FATAL EXCEPTION: main
08-10 23:04:50.145: E/AndroidRuntime(1415): java.lang.NullPointerException
08-10 23:04:50.145: E/AndroidRuntime(1415): at java.util.regex.Matcher.appendEvaluated>(Matcher.java:130)
08-10 23:04:50.145: E/AndroidRuntime(1415): at java.util.regex.Matcher.appendReplacement(Matcher.java:110)
08-10 23:04:50.145: E/AndroidRuntime(1415): at java.util.regex.Matcher.replaceFirst(Matcher.java:299)
08-10 23:04:50.145: E/AndroidRuntime(1415): at java.lang.String.replaceFirst(String.java:1793)
08-10 23:04:50.145: E/AndroidRuntime(1415): at com.muirconsult.mymadlibs.FormActivity$MadLibAsyncTask.onPostExecute(FormActivity.java:116)
08-10 23:04:50.145: E/AndroidRuntime(1415): at com.muirconsult.mymadlibs.FormActivity$MadLibAsyncTask.onPostExecute(FormActivity.java:1)
08-10 23:04:50.145: E/AndroidRuntime(1415): at android.os.AsyncTask.finish(AsyncTask.java:631)
08-10 23:04:50.145: E/AndroidRuntime(1415): at android.os.AsyncTask.access$600>\ (AsyncTask.java:177)
08-10 23:04:50.145: E/AndroidRuntime(1415): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
08-10 23:04:50.145: E/AndroidRuntime(1415): at android.os.Handler.dispatchMessage(Handler.java:99)
08-10 23:04:50.145: E/AndroidRuntime(1415): at android.os.Looper.loop(Looper.java:137)
08-10 23:04:50.145: E/AndroidRuntime(1415): at android.app.ActivityThread.main(ActivityThread.java:5041)
08-10 23:04:50.145: E/AndroidRuntime(1415): at java.lang.reflect.Method.invokeNative(Native Method)
08-10 23:04:50.145: E/AndroidRuntime(1415): at java.lang.reflect.Method.invoke(Method.java:511)
08-10 23:04:50.145: E/AndroidRuntime(1415): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-10 23:04:50.145: E/AndroidRuntime(1415): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-10 23:04:50.145: E/AndroidRuntime(1415): at dalvik.system.NativeStart.main(Native Method)

Related

JavaFX Date Picker specific format error

I've created a Sample Application which uses JavaFX-8 Date Picker. It works fine on default pattern but on a specific pattern it throws a exception. I'm trying to convert it on 'DD-MM-YYYY' pattern on default.
Here is the Source File of the Program
Please take a look.
DatePickerController.java
package javafx.datepicker;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TextArea;
import javafx.util.StringConverter;
public class DatePickerController {
#FXML
private DatePicker dp;
#FXML
private Button btn;
#FXML
private TextArea ta;
public void initialize() {
String pattern = "DD-MM-YYYY";
dp.setPromptText(pattern);
try {
dp.setConverter(new StringConverter<LocalDate>() {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
#Override
public String toString(LocalDate object) {
if (object == null) {
return null;
}
return dtf.format(object);
}
#Override
public LocalDate fromString(String string) {
if (string != null & !string.isEmpty()) {
return LocalDate.parse(string, dtf);
}
return null;
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
And here is Main Class
JavaFXDatePicker.java
package javafx.datepicker;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class JavaFXDatePicker extends Application {
public static void main(String... args) {
launch(args);
}
#Override
public void start(Stage st) {
try {
Parent root = FXMLLoader.load(getClass().getResource("/javafx/datepicker/DatePicker.fxml"));
Scene sc = new Scene(root);
st.setScene(sc);
st.setTitle("JavaFX Date Picker");
st.show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
And Here is FXML File
DatePicker.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="247.0" prefWidth="372.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8" fx:controller="javafx.datepicker.DatePickerController">
<children>
<DatePicker fx:id="dp" layoutX="50.0" layoutY="51.0" prefHeight="25.0" prefWidth="273.0" />
<Button fx:id="btn" layoutX="50.0" layoutY="99.0" mnemonicParsing="false" prefHeight="25.0" prefWidth="273.0" text="Click" />
<TextArea fx:id="ta" layoutX="50.0" layoutY="133.0" prefHeight="89.0" prefWidth="273.0" />
</children>
</AnchorPane>
And here is the stacktarce of the error
Exception in thread "JavaFX Application Thread" java.time.DateTimeException: Field DayOfYear cannot be printed as the value 196 exceeds the maximum print width of 2
at java.time.format.DateTimeFormatterBuilder$NumberPrinterParser.format(DateTimeFormatterBuilder.java:2548)
at java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2179)
at java.time.format.DateTimeFormatter.formatTo(DateTimeFormatter.java:1746)
at java.time.format.DateTimeFormatter.format(DateTimeFormatter.java:1720)
at javafx.datepicker.DatePickerController$1.toString(DatePickerController.java:45)
at javafx.datepicker.DatePickerController$1.toString(DatePickerController.java:37)
at com.sun.javafx.scene.control.skin.ComboBoxPopupControl.updateDisplayNode(ComboBoxPopupControl.java:424)
at com.sun.javafx.scene.control.skin.DatePickerSkin.handleControlPropertyChanged(DatePickerSkin.java:141)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase.lambda$registerChangeListener$61(BehaviorSkinBase.java:197)
at com.sun.javafx.scene.control.MultiplePropertyChangeListenerHandler$1.changed(MultiplePropertyChangeListenerHandler.java:55)
at javafx.beans.value.WeakChangeListener.changed(WeakChangeListener.java:89)
at com.sun.javafx.binding.ExpressionHelper$Generic.fireValueChangedEvent(ExpressionHelper.java:361)
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81)
at javafx.beans.property.ObjectPropertyBase.fireValueChangedEvent(ObjectPropertyBase.java:105)
at javafx.beans.property.ObjectPropertyBase.markInvalid(ObjectPropertyBase.java:112)
at javafx.beans.property.ObjectPropertyBase.set(ObjectPropertyBase.java:146)
at javafx.scene.control.ComboBoxBase.setValue(ComboBoxBase.java:150)
at com.sun.javafx.scene.control.skin.DatePickerContent.selectDayCell(DatePickerContent.java:689)
at com.sun.javafx.scene.control.skin.DatePickerContent.lambda$createDayCells$174(DatePickerContent.java:731)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$ClickGenerator.postProcess(Scene.java:3470)
at javafx.scene.Scene$ClickGenerator.access$8100(Scene.java:3398)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3766)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:380)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:294)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:416)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:415)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:745)
I tried almost every method to resolve this but always bad luck.
Please give me suggestions to resolve this and also explain this error.
I think you want the following:
String pattern = "dd-MM-yyyy";

"java.lang.NullPointerException" Error when trying to insert data to sqlite (Android)

I face the error :
1566-1566/com.example.rom.romproject E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.rom.romproject, PID: 1566
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3823)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3818)
            at android.view.View.performClick(View.java:4438)
            at android.view.View$PerformClick.run(View.java:18422)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.rom.romproject.ContactView.contactFavorite(ContactView.java:37)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at android.view.View$1.onClick(View.java:3818)
            at android.view.View.performClick(View.java:4438)
            at android.view.View$PerformClick.run(View.java:18422)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)
This happens when im clicking on a button i created.
The button purpose is to insert Data into my sql table.
The SQL class :
public class sqlDatabaseAdapter
{
sqlHelper helper;
public sqlDatabaseAdapter(Context context)
{
helper = new sqlHelper(context);
}
public long insertData(String name, String phone)
{
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues content = new ContentValues();
content.put(sqlHelper.NAME, name);
content.put(sqlHelper.PHONE, phone);
return db.insert(helper.TABLE_NAME, null, content);
}
static class sqlHelper extends SQLiteOpenHelper
{
static final String DATABASE_NAME = "ContactDB";
static final String TABLE_NAME = "Favorites";
static final int DB_VERSION = 1;
static final String UID = "_id";
static final String NAME = "Name";
static final String PHONE = "Phone";
static final String CREATE_TABLE = "CREATE TABLE "+ TABLE_NAME +" ("+UID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(255), "+PHONE+" VARCHAR(255));";
static final String DROP_TABLE = "DROP TABLE IF EXISTS"+TABLE_NAME;
private Context context;
public sqlHelper(Context context)
{
super(context, DATABASE_NAME, null, DB_VERSION);
this.context = context;
Message.Message(context, "Constructor Called");
}
#Override
public void onCreate(SQLiteDatabase db)
{
try {
db.execSQL(CREATE_TABLE);
Message.Message(context, "onCreate Called");
} catch( SQLException e)
{
Message.Message(context, "" + e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
try {
db.execSQL(DROP_TABLE);
onCreate(db);
Message.Message(context, "OnUpgrade Called");
} catch(SQLException e)
{
Message.Message(context, "" + e);
}
}
}
}
Now, im not rly sure at the source of the problem , so i will post both of my activites.
Btw : the info im trying to insert to the SQL is a contact name and phone
(that i get from the main activity list view).
Main Activity ( List view of phone contacts ) :
public class MainActivity extends ListActivity {
ListView l;
Cursor cursor;
SimpleCursorAdapter listAdapter;
sqlDatabaseAdapter helper;
#Override
public int getSelectedItemPosition()
{
return super.getSelectedItemPosition();
}
#Override
public long getSelectedItemId()
{
return super.getSelectedItemId();
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
startManagingCursor(cursor);
String[] from = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone._ID};
int[] to = {android.R.id.text1,android.R.id.text2};
listAdapter = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_2,cursor,from,to);
setListAdapter(listAdapter);
l = getListView();
l.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
helper = new sqlDatabaseAdapter(this);
helper.helper.getWritableDatabase();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
TextView _tempName= (TextView)v.findViewById(android.R.id.text1);
String _temp = _tempName.getText().toString();
TextView _tempPhone = (TextView)v.findViewById(android.R.id.text2);
String _temp2 = _tempPhone.getText().toString();
Intent intent = new Intent(this, ContactView.class);
intent.putExtra("contactName", _temp);
intent.putExtra("contactPhone", _temp2);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The second activity (where the button is ) :
public class ContactView extends ActionBarActivity {
Button _Call;
Button _Favorite;
FavoriteContact contact = new FavoriteContact();
sqlDatabaseAdapter helper;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_view);
_Call = (Button)findViewById(R.id.bCall);
_Favorite = (Button)findViewById(R.id.bFavorite);
contact.setName(getIntent().getExtras().getString("contactName"));
contact.setPhone(getIntent().getExtras().getString("contactPhone"));
setTitle(contact.getName());
}
public void contactFavorite(View view)
{
long id = 0L;
id = helper.insertData(contact.getName(), contact.getPhone());
/*
if( id < 0)
{
Message.Message(this, "Unsuccessful");
}
else
{
Message.Message(this, "Successfully inserted to favorite contacts ");
}
*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_contact_view, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Contact class i created and FavoriteContact class :
(favoritecontact extends Contact)
public class Contact
{
private String Name = null;
private String Phone = null;
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}
public class FavoriteContact extends Contact
{
private Boolean isFavorite;
public Boolean getIsFavorite() {
return isFavorite;
}
public void setIsFavorite(Boolean isFavorite) {
this.isFavorite = isFavorite;
}
}
i think i gave everything i need...
sorry for my bad english and its my first time posting here so i dont rly know how it works :D
thanks for every bit of help .
The variable helper is never initialized in ContactView.

Android: java.lang.nullPointerException at custom ListView adapter

I'm trying to make a custom view for my ListView, but the app crash when try to open it. I read a lot of pages but don't find the solution. Please help me!
This is my custom Adapter:
public class AdaptadorCatalogo extends BaseAdapter {
protected Activity activity;
protected ArrayList<LineaCatalogo> items;
public AdaptadorCatalogo(Activity activity, ArrayList<LineaCatalogo> items) {
this.activity = activity;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position){
return 0;
}
#Override
public View getView(int position, View contentView, ViewGroup parent) {
View vi=contentView;
if(contentView == null) {
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = inflater.inflate(R.layout.listitem_catalogo, null);
}
LineaCatalogo item = items.get(position);
TextView primeraLinea = (TextView) vi.findViewById(R.id.lblPrimeraLinea);
primeraLinea.setText(item.getPrimeraLinea());
TextView segundaLinea = (TextView) vi.findViewById(R.id.lblSegundaLinea);
segundaLinea.setText(item.getSegundaLinea());
TextView magnitud = (TextView) vi.findViewById(R.id.lblMagnitud);
magnitud.setText(item.getMagnitud());
return vi;
}
}
This is my xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".listaSismos" >
<RelativeLayout
android:id="#+id/general"
style="#style/AppCentral"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="50dp" >
<TextView
android:id="#+id/titulo_catalogo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:text="#string/esperando_info" />
<ListView
android:id="#+id/listaDatos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginBottom="50dp"
android:layout_marginTop="50dp"
android:layout_marginLeft="30dp" />
</RelativeLayout>
</RelativeLayout>
This is my Activity:
public class listaSismos extends Activity {
private TextView tituloCatalogo;
private ListView listaDatos;
private String opcion;
private String codigoUsuario;
private String latitud;
private String longitud;
private String idioma;
private int difHoraria;
private ArrayList<LineaCatalogo> Catalogo;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.lista_sismos);
tituloCatalogo = (TextView)findViewById(R.id.titulo_catalogo);
listaDatos = (ListView)findViewById(R.id.listaDatos);
Bundle bundle = getIntent().getExtras();
opcion = bundle.getString("lista");
codigoUsuario = bundle.getString("codigoUsuario");
latitud = bundle.getString("latitud");
longitud = bundle.getString("longitud");
idioma = getResources().getConfiguration().locale.toString();
TimeZone defaultTZ = TimeZone.getDefault();
difHoraria = defaultTZ.getRawOffset() / 1000;
ListarCatalogo conexion = new ListarCatalogo();
conexion.execute();
}
#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;
}
private class ListarCatalogo extends AsyncTask<String,Integer,Boolean> {
private int contador;
protected Boolean doInBackground(String... params) {
boolean resul = true;
HttpClient httpClient = new DefaultHttpClient();
HttpGet del =
new HttpGet(my_app_server_url);
del.setHeader("content-type", "application/json");
try
{
HttpResponse resp = httpClient.execute(del);
String respStr = EntityUtils.toString(resp.getEntity());
JSONArray respJSON = new JSONArray(respStr);
ArrayList<LineaCatalogo> Catalogo = new ArrayList<LineaCatalogo>();
contador = respJSON.length();
for(int cont=0; cont<contador; cont++)
{
JSONObject obj = respJSON.getJSONObject(cont);
String tituloS = obj.getString("P");
String subtituloS = obj.getString("S");
String magnitudS = obj.getString("M");
Catalogo.add(new LineaCatalogo(tituloS, subtituloS, magnitudS));
}
}
catch(Exception ex)
{
resul = false;
}
return resul;
}
protected void onPostExecute(Boolean result) {
tituloCatalogo.setText(R.string.titulo_catalogo);
if (result)
{
//Rellenamos la lista con los resultados
AdaptadorCatalogo adaptador = new AdaptadorCatalogo(listaSismos.this, Catalogo);
listaDatos.setAdapter(adaptador);
tituloCatalogo.setText("OK");
} else {
tituloCatalogo.setText(R.string.no_datos);
}
}
}
}
If i comment the line "listaDatos.setAdapter(adaptador);", the app runs ok. If not, i get this LogCat:
12-06 09:34:32.443: W/dalvikvm(903): threadid=1: thread exiting with uncaught exception (group=0x41465700)
12-06 09:34:32.559: E/AndroidRuntime(903): FATAL EXCEPTION: main
12-06 09:34:32.559: E/AndroidRuntime(903): java.lang.NullPointerException
12-06 09:34:32.559: E/AndroidRuntime(903): at com.tapsistemas.avcanquake.AdaptadorCatalogo.getCount(AdaptadorCatalogo.java:23)
12-06 09:34:32.559: E/AndroidRuntime(903): at android.widget.ListView.setAdapter(ListView.java:463)
12-06 09:34:32.559: E/AndroidRuntime(903): at com.tapsistemas.avcanquake.listaSismos$ListarCatalogo.onPostExecute(listaSismos.java:124)
12-06 09:34:32.559: E/AndroidRuntime(903): at com.tapsistemas.avcanquake.listaSismos$ListarCatalogo.onPostExecute(listaSismos.java:1)
12-06 09:34:32.559: E/AndroidRuntime(903): at android.os.AsyncTask.finish(AsyncTask.java:631)
12-06 09:34:32.559: E/AndroidRuntime(903): at android.os.AsyncTask.access$600(AsyncTask.java:177)
12-06 09:34:32.559: E/AndroidRuntime(903): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
12-06 09:34:32.559: E/AndroidRuntime(903): at android.os.Handler.dispatchMessage(Handler.java:99)
12-06 09:34:32.559: E/AndroidRuntime(903): at android.os.Looper.loop(Looper.java:137)
12-06 09:34:32.559: E/AndroidRuntime(903): at android.app.ActivityThread.main(ActivityThread.java:5103)
12-06 09:34:32.559: E/AndroidRuntime(903): at java.lang.reflect.Method.invokeNative(Native Method)
12-06 09:34:32.559: E/AndroidRuntime(903): at java.lang.reflect.Method.invoke(Method.java:525)
12-06 09:34:32.559: E/AndroidRuntime(903): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-06 09:34:32.559: E/AndroidRuntime(903): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-06 09:34:32.559: E/AndroidRuntime(903): at dalvik.system.NativeStart.main(Native Method)
I still working a week looking for the solution, but i can't do it. Please, help me. And sorry by my poor english, i'm spanish from Canary Islands.
Declare and initialize like
private ArrayList<LineaCatalogo> Catalogo= new ArrayList<LineaCatalogo>();
#Override
public void onCreate(Bundle savedInstanceState){
Remove
ArrayList<LineaCatalogo> Catalogo = new ArrayList<LineaCatalogo>();
// becomes local to doInbackground as it is declared and initialized there.
in doInbackground.
In your case Catalogo was null.
You redefine your list with
ArrayList<LineaCatalogo> Catalogo = new ArrayList<LineaCatalogo>();
in the doInBacground
use just
Catalogo = new ArrayList<LineaCatalogo>();

CompileError in File uploading

List<?> items =upload.parseRequest(request);
The method parseRequest(HttpServletRequest, int, long, String) in the type DiskFileUpload is not applicable for the arguments (HttpServletRequest)
When i Run as Server...it gives error on console
May 13, 2012 7:47:49 PM org.apache.tomcat.util.digester.Digester startElement
SEVERE: Begin event threw error
java.lang.NoSuchMethodError: org.apache.tomcat.util.ExceptionUtils.unwrapInvocationTargetException(Ljava/lang/Throwable;)Ljava/lang/Throwable;
at org.apache.catalina.core.AprLifecycleListener.init(AprLifecycleListener.java:185)
at org.apache.catalina.core.AprLifecycleListener.isAprAvailable(AprLifecycleListener.java:84)
at org.apache.catalina.connector.Connector.setProtocol(Connector.java:577)
at org.apache.catalina.connector.Connector.(Connector.java:69)
at org.apache.catalina.startup.ConnectorCreateRule.begin(ConnectorCreateRule.java:62)
at org.apache.tomcat.util.digester.Digester.startElement(Digester.java:1356)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:506)
at com.sun.org.apache.xerces.internal.parsers.AbstractXMLDocumentParser.emptyElement(AbstractXMLDocumentParser.java:182)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(XMLDocumentFragmentScannerImpl.java:1302)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2715)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:607)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:488)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:835)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:123)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1210)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:568)
at org.apache.tomcat.util.digester.Digester.parse(Digester.java:1642)
at org.apache.catalina.startup.Catalina.load(Catalina.java:576)
at org.apache.catalina.startup.Catalina.load(Catalina.java:619)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:281)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:449)
java.lang.NoSuchMethodError: org.apache.tomcat.util.ExceptionUtils.unwrapInvocationTargetException(Ljava/lang/Throwable;)Ljava/lang/Throwable;
at org.apache.catalina.core.AprLifecycleListener.init(AprLifecycleListener.java:185)
at org.apache.catalina.core.AprLifecycleListener.isAprAvailable(AprLifecycleListener.java:84)
at org.apache.catalina.connector.Connector.setProtocol(Connector.java:577)
at org.apache.catalina.connector.Connector.(Connector.java:69)
at org.apache.catalina.startup.ConnectorCreateRule.begin(ConnectorCreateRule.java:62)
at org.apache.tomcat.util.digester.Digester.startElement(Digester.java:1356)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:506)
at com.sun.org.apache.xerces.internal.parsers.AbstractXMLDocumentParser.emptyElement(AbstractXMLDocumentParser.java:182)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(XMLDocumentFragmentScannerImpl.java:1302)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2715)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:607)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:488)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:835)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:123)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1210)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:568)
at org.apache.tomcat.util.digester.Digester.parse(Digester.java:1642)
at org.apache.catalina.startup.Catalina.load(Catalina.java:576)
at org.apache.catalina.startup.Catalina.load(Catalina.java:619)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:281)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:449)
This is my code in this code
List<?> items =upload.parseRequest(request); Got error as The method parseRequest(HttpServletRequest, int, long, String) in the type DiskFileUpload is not applicable for the arguments
(HttpServletRequest)
package br.com.ecommerce.servlet;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.disk.*;
import org.apache.tomcat.util.http.fileupload.servlet.*;
import org.apache.tomcat.util.http.fileupload.util.*;
import org.apache.tomcat.util.http.fileupload.DiskFileUpload;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileUpload;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.RequestContext;
import br.com.ecommerce.bean.Produtos;
import br.com.ecommerce.controller.ExceptionController;
import br.com.ecommerce.dao.CategoriasDao;
import br.com.ecommerce.dao.ProdutosDao;
class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public UploadServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
Produtos produto = new Produtos();
String caminhoTemp = new String("C:\\Users\\vaio\\workspace\\ecommerce\\WebContent\\images\\upload");
String pasta = new String("C:\\Users\\vaio\\workspace\\ecommerce\\WebContent\\images\\upload");
String caminho = new String("images\\upload\\");
if (ServletFileUpload.isMultipartContent( request)){
DiskFileUpload upload = new DiskFileUpload();
upload.setRepositoryPath(caminhoTemp);
try{
List<?> items =upload.parseRequest(request);//In this line i got error..why?..Pls help
Iterator<?> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if(item.isFormField()){
if(item.getFieldName().equals("nome")){
produto.setProdNome(item.getString().toUpperCase());
}
else if (item.getFieldName().equals("categoria")){
produto.setCategorias(new CategoriasDao().findByPK(Integer.valueOf(item.getString())));
}
else if (item.getFieldName().equals("preco")){
produto.setPreco(Double.valueOf(item.getString()));
Double preco = 0d;
preco = Double.valueOf(item.getString());
preco += 10.00;
System.out.println(preco);
}
else if (item.getFieldName().equals("descp")){
produto.setDescPeq(item.getString());
}
else if (item.getFieldName().equals("descg")){
produto.setDescGd(item.getString());
}
else if (item.getFieldName().equals("espec")){
produto.setEspecificacoes(item.getString());
}
else if (item.getFieldName().equals("itens")){
produto.setItensInclusos(item.getString());
}
produto.setPromocao(0);
produto.setDestaque(0);
}
if (!item.isFormField()) {
String nome = item.getName().toString();
String nomeArquivo = nome.substring(nome.lastIndexOf("\\")+1);
File arquivo = new File(pasta + "\\" + nomeArquivo);
produto.setImagem(caminho + nomeArquivo);
item.write(arquivo);
}
}
}catch(FileUploadException e){
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
try {
new ProdutosDao().insert(produto);
} catch (ExceptionController e) {
e.printStackTrace();
}
response.sendRedirect("/ecommerce/admin/gerenciarProdutos.jsp");
}
}
enter code here
Are you trying to use the DiskFileUpload class from Commons FileUpload? If so, make sure your class is importing org.apache.commons.fileupload.DiskFileUpload, and not some other class called DiskFileUpload.

GWT Uncaught exception escaped

I have created a new google application using GWT, and it runs fine. But when i click a button that is responsible for performing some action with the server side, it throws an unusual error. Please could someone offer some help? Thank you in advance :(
Here is the code:
package com.ukstudentfeedback.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.ukstudentfeedback.shared.FieldVerifier;
import com.ukstudentfeedback.client.MailClient;
import com.ukstudentfeedback.client.MailClientAsync;
public class Ukstudentfeedback implements EntryPoint{
private static final String SERVER_ERROR = "An error occurred while "
+ "attempting to contact the server. Please check your network "
+ "connection and try again.";
/**
* Create a remote service proxy to talk to the server-side Greeting service.
*/
private final MailClientAsync sendMessage = GWT
.create(MailClient.class);
// ...
public void onModuleLoad()
{
java.lang.System.out.println("I finally worked!");
final Button sendButton;
final TextBox toField, fromField, subjectField, messageField;
final Label errorLabel = new Label();
sendButton = new Button("Send");
toField = new TextBox();
fromField = new TextBox();
subjectField = new TextBox();
messageField = new TextBox();
sendButton.addStyleName("sendButton");
toField.setText("Testing");
// Add the nameField and sendButton to the RootPanel
// Use RootPanel.get() to get the entire body element
RootPanel.get("sendButton").add(sendButton);
RootPanel.get("To").add(toField);
RootPanel.get("From").add(fromField);
RootPanel.get("Subject").add(subjectField);
RootPanel.get("Message").add(messageField);
RootPanel.get("errorLabelContainer").add(errorLabel);
// Focus the cursor on the to field when the app loads
toField.setFocus(true);
toField.selectAll();
//sendButton.setEnabled(true);
// Create the popup dialog box
final DialogBox dialogBox = new DialogBox();
dialogBox.setText("Message Sent");
dialogBox.setAnimationEnabled(true);
final Button closeButton = new Button("Close");
// We can set the id of a widget by accessing its Element
closeButton.getElement().setId("closeButton");
final Label textToServerLabel = new Label();
final HTML serverResponseLabel = new HTML();
VerticalPanel dialogVPanel = new VerticalPanel();
dialogVPanel.addStyleName("dialogVPanel");
dialogVPanel.add(new HTML("<b>Message Sent:</b>"));
dialogVPanel.add(textToServerLabel);
dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
dialogVPanel.add(serverResponseLabel);
dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
dialogVPanel.add(closeButton);
dialogBox.setWidget(dialogVPanel);
// Add a handler to close the DialogBox
closeButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
dialogBox.hide();
sendButton.setEnabled(true);
sendButton.setFocus(true);
}
});
// Create a handler for the sendButton and nameField
class MyHandler implements ClickHandler{
/**
* Fired when the user clicks on the sendButton.
*/
public void onClick(ClickEvent event) {
java.lang.System.out.println("I have been clicked");
sendMessageToServer();
}
public void sendMessageToServer()
{
errorLabel.setText("");
String to = toField.getText();
String from = fromField.getText();
String subject = subjectField.getText();
String message = messageField.getText();
if (!FieldVerifier.isValidName(to, from, subject, message)) {
errorLabel.setText("Please enter at least four characters");
return;
}
sendButton.setEnabled(false);
textToServerLabel.setText("Hello");
serverResponseLabel.setText("");
sendMessage.sendMessage(to, from, subject, message, new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
dialogBox
.setText("Message sending Failed");
serverResponseLabel
.addStyleName("serverResponseLabelError");
serverResponseLabel.setHTML(SERVER_ERROR);
dialogBox.center();
closeButton.setFocus(true);
}
public void onSuccess(String result) {
dialogBox.setText("Message Sent");
serverResponseLabel
.removeStyleName("serverResponseLabelError");
serverResponseLabel.setHTML(result);
dialogBox.center();
closeButton.setFocus(true);
}
});
}
}
// Add a handler to send the name to the server
MyHandler handler = new MyHandler();
sendButton.addClickHandler(handler);
}
}
Server side:
package com.ukstudentfeedback.server;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.ukstudentfeedback.shared.FieldVerifier;
#SuppressWarnings("serial")
public class MailServerImpl extends RemoteServiceServlet{
public void sendMessage(String to, String from, String subject, String message) throws IllegalArgumentException
{
// Verify that no input is null.
if (!FieldVerifier.isValidName(to, from, subject, message)) {
// If the input is not valid, throw an IllegalArgumentException back to
// the client.
throw new IllegalArgumentException(
"Name must be at least 4 characters long");
}
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
try
{
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from, "Admin"));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(to, "Mr. User"));
msg.setSubject(subject);
msg.setText(message);
Transport.send(msg);
}
catch (AddressException e)
{
// ...
e.printStackTrace();
} catch (MessagingException e)
{
// ...
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Error Stack:
23:26:55.817 [ERROR] [ukstudentfeedback] Uncaught exception escaped
com.google.gwt.event.shared.UmbrellaException: One or more exceptions caught, see full set in UmbrellaException#getCauses
at com.google.gwt.event.shared.HandlerManager.fireEvent(HandlerManager.java:129)
at com.google.gwt.user.client.ui.Widget.fireEvent(Widget.java:129)
at com.google.gwt.event.dom.client.DomEvent.fireNativeEvent(DomEvent.java:116)
at com.google.gwt.user.client.ui.Widget.onBrowserEvent(Widget.java:177)
at com.google.gwt.user.client.DOM.dispatchEventImpl(DOM.java:1351)
at com.google.gwt.user.client.DOM.dispatchEvent(DOM.java:1307)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessagesWhileWaitingForReturn(BrowserChannelServer.java:337)
at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:218)
at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136)
at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:561)
at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:269)
at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91)
at com.google.gwt.core.client.impl.Impl.apply(Impl.java)
at com.google.gwt.core.client.impl.Impl.entry0(Impl.java:213)
at sun.reflect.GeneratedMethodAccessor27.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessages(BrowserChannelServer.java:292)
at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:546)
at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:363)
at java.lang.Thread.run(Thread.java:680)
Caused by: com.google.gwt.user.client.rpc.ServiceDefTarget$NoServiceEntryPointSpecifiedException: Service implementation URL not specified
at com.google.gwt.user.client.rpc.impl.RemoteServiceProxy.doPrepareRequestBuilderImpl(RemoteServiceProxy.java:430)
at com.google.gwt.user.client.rpc.impl.RemoteServiceProxy.doInvoke(RemoteServiceProxy.java:368)
at com.google.gwt.user.client.rpc.impl.RemoteServiceProxy$ServiceHelper.finish(RemoteServiceProxy.java:74)
at com.ukstudentfeedback.client.MailClient_Proxy.sendMessage(MailClient_Proxy.java:38)
at com.ukstudentfeedback.client.Ukstudentfeedback$1MyHandler.sendMessageToServer(Ukstudentfeedback.java:118)
at com.ukstudentfeedback.client.Ukstudentfeedback$1MyHandler.onClick(Ukstudentfeedback.java:98)
at com.google.gwt.event.dom.client.ClickEvent.dispatch(ClickEvent.java:54)
at com.google.gwt.event.dom.client.ClickEvent.dispatch(ClickEvent.java:1)
at com.google.gwt.event.shared.GwtEvent.dispatch(GwtEvent.java:1)
at com.google.web.bindery.event.shared.EventBus.dispatchEvent(EventBus.java:40)
at com.google.web.bindery.event.shared.SimpleEventBus.doFire(SimpleEventBus.java:193)
at com.google.web.bindery.event.shared.SimpleEventBus.fireEvent(SimpleEventBus.java:88)
at com.google.gwt.event.shared.HandlerManager.fireEvent(HandlerManager.java:127)
at com.google.gwt.user.client.ui.Widget.fireEvent(Widget.java:129)
at com.google.gwt.event.dom.client.DomEvent.fireNativeEvent(DomEvent.java:116)
at com.google.gwt.user.client.ui.Widget.onBrowserEvent(Widget.java:177)
at com.google.gwt.user.client.DOM.dispatchEventImpl(DOM.java:1351)
at com.google.gwt.user.client.DOM.dispatchEvent(DOM.java:1307)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessagesWhileWaitingForReturn(BrowserChannelServer.java:337)
at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:218)
at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136)
at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:561)
at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:269)
at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91)
at com.google.gwt.core.client.impl.Impl.apply(Impl.java)
at com.google.gwt.core.client.impl.Impl.entry0(Impl.java:213)
at sun.reflect.GeneratedMethodAccessor27.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessages(BrowserChannelServer.java:292)
at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:546)
at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:363)
at java.lang.Thread.run(Thread.java:680)
To find the cause of an UmbrellaException look for "Caused by":
Caused by:
com.google.gwt.user.client.rpc.ServiceDefTarget$NoServiceEntryPointSpecifiedException:
Service implementation URL not specified
Specify the remote service URL by doing either of the following:
Adding a RemoteServiceRelativePath annotation to your MailClientAsync interface.
Calling ServiceDefTarget#setServiceEntryPoint:
((ServiceDefTarget)sendMessage).
setServiceEntryPoint("http://www.example.com/service");