Java Update Query does not work - sql-update

I have data access object factory class. There are two methods: one to retrieve data and one to update table. The method which retrieves data works properly. But the update method does not work. I cannot figure out the problem. Please help.
This is the factory class:
public class ChequeDAOImpl implements ChequeDAO {
public DBConnect dbConnection;
#Override
public List<Cheque> getCheques() throws SQLException{
List<Cheque> cheques = new ArrayList<Cheque>();
Connection connection = dbConnection.getConnection();
try{
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery("select * from TblProj");
while(result.next()) {
Cheque cheque = new Cheque();
cheque.setName(result.getString("Name"));
cheque.setAmount(result.getDouble("Amount"));
cheque.setDate(result.getDate("Date"));
cheque.setChqNum(result.getString("CNumber"));
cheque.setValue(result.getDouble("Value"));
cheques.add(cheque);
}
}catch(Exception exception){
exception.printStackTrace();
}finally{
connection.close();
}
return cheques;
}
#Override
public void updateFlag(String chNum) throws SQLException{
DBConnect Connection = null;
Connection conn = Connection.getConnection();
try{
PreparedStatement stmt = (PreparedStatement) conn.prepareStatement("UPDATE TblProj SET flag = ? WHERE CNumber = ? ");
int i= stmt.executeUpdate();
stmt.setString(1, "1");
stmt.setString(2, chNum);
if(i>0)
{
JOptionPane.showMessageDialog(null, "Updated successfully");
}
}
catch(Exception ex){
JOptionPane.showMessageDialog(null, ex.toString());
}
finally{
conn.close();
}
}
public DBConnect getConnection() {
return dbConnection;
}
public void setConnection(DBConnect connection) {
this.dbConnection = connection;
}
}
This is the how I have used updateFlag method:
dao.updateFlag(gui.chqNo);

Pls rewrite your prepared statement as bellow, first set the parameter for prepared statement and than execute with executeUpdate() method.
PreparedStatement stmt = (PreparedStatement) conn.prepareStatement("UPDATE TblProj SET flag = ? WHERE CNumber = ? ");
stmt.setInt(1, 1);
stmt.setString(2, chNum);
int i= stmt.executeUpdate();

Related

Change Activity into Fragment

I am quite new at Android.
So I am a bit confused of working with fragments.
I have found a very great tutorial.
So I have working code. But it is the layout oft a normal activity.
Then I tried to include it into a navigation drawer.
So the list view with data will only be shown when the menu item has been selected.
On the fragment View there is a never ending loading Dialog.
While debugging I have figured out that the code loads still the data and inserts it into feedItems.
So feedItems is filled correctly.
Now after listAdapter.notifyDataSetChanged() there happens nothing.
So here that is my code:
public class FragmentNews extends ListFragment {
private static final String TAG = FragmentNews.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private String URL_FEED = "http://address.com";
public FragmentNews(){}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
loadDataForNews();
}
private void loadDataForNews(){
listView = this.getListView();
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(getActivity(), feedItems);
listView.setAdapter(listAdapter);
// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(URL_FEED);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
}
// List View Feed
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Can the problem be that the inflater of listAdapter is null?
Thanks for help!
Sometimes listAdapter.notifyDataSetChanged() does not work properly.
Try removing
listAdapter = new FeedListAdapter(getActivity(), feedItems);
listView.setAdapter(listAdapter);
from loadDataForNews() and adding in
place of listAdapter.notifyDataSetChanged();

JMockit - mock CXF webservice port object

I'm trying to unit test a webservice wrapper class which attempts to hide all the webservice implementation details. It's called from a scripting platform so all interfaces are simple String or integers. The class provides a static initialise method which takes the hostname and port number and uses this to create a private static Apache CXF IRemote port instance (generated from CXF wsdl2java). Subsequent calls to a static business method delegate to the port instance.
How can I use JMockit to mock the CXF port stub when unit testing the static wrapper class?
public class WebServiceWrapper {
private static final QName SERVICE_NAME = new QName("http://www.gwl.org/example/service",
"ExampleService");
private static IRemoteExample _port = null;
public static final String initialise(String url) {
if(_port != null) return STATUS_SUCCESS;
try {
URL wsdlURL = new URL(url);
ExampleService svc = new ExampleService(wsdlURL, SERVICE_NAME);
_port = svc.getIRemoteExamplePort();
BindingProvider bp = (BindingProvider)_port;
Map<String, Object> context = bp.getRequestContext();
context.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true);
return STATUS_SUCCESS;
}
catch(MalformedURLException ex) {
return STATUS_ERROR_PREFIX + ex.getMessage();
}
catch(WebServiceException ex) {
return STATUS_ERROR_PREFIX + ex.getMessage();
}
}
public static final String businessMethod(String arg) {
if(_port == null) {
return STATUS_ERROR_PREFIX + "Attempted to call businessMethod before connection is initialised. Pease call initialise first.";
}
try {
BusinessMethodRequest request = new BusinessMethodRequest ();
BusinessThing thing = new BusinessThing();
thing.setValue(arg);
request.setThing(thing);
BusinessMethodResponse response = _port.businessMethod(request);
String result = response.getResult();
if(result == null) {
return STATUS_ERROR_PREFIX + "Null returned!";
}
return STATUS_SUCCESS;
}
catch(MyBusinessException_Exception ex) {
return STATUS_ERROR_PREFIX + ex.getFaultInfo().getReason();
}
catch(WebServiceException ex) {
return STATUS_ERROR_PREFIX + ex.getMessage();
}
}
Example behaviour of the webservice would be, if I pass the value "OK" then it returns a success message, but if I call with a value of "DUPLICATE" then the webservice would throw a MyBusinessException_Exception.
I think I have managed to mock the _port object, but the business call always returns a null Response object so I suspect that my Expectations does not define the "BusinessThing" object correctly. My Test method so far.
#Test
public void testBusinessMethod(#Mocked final IRemoteExample port) {
new NonStrictExpectations() {
#Capturing IRemoteExample port2;
{
BusinessThing thing = new BusinessThing();
thing.setValue("OK");
BusinessMethodRequest req = new BusinessMeothdRequest();
req.setThing(thing);
BusinessMethodResponse resp = new BusinessMethodResponse ();
resp.setResult("SUCCESS");
try {
port.businessMethod(req);
returns(resp);
}
catch(MyBusinessException_Exception ex) {
returns(null);
}
Deencapsulation.setField(WebServiceWrapper.class, "_port", port);
}
};
String actual = WebServiceWrapper.businessMethod("OK");
assertEquals(WebServiceWrapper.STATUS_SUCCESS, actual);
}
Seems to be working as follows.
Added a custom Matcher class for my BusinessMethodRequest
class BusinessMethodRequestMatcher extends TypeSafeMatcher<BusinessMethodRequest> {
private final BusinessMethodRequestexpected;
public BusinessMethodRequestMatcher(BusinessMethodRequest expected) {
this.expected. = expected;
}
#Override
public boolean matchesSafely(BusinessMethodRequest actual) {
// could improve with null checks
return expected.getThing().getValue().equals(actual.getThing().getValue());
}
#Override
public void describeTo(Description description) {
description.appendText(expected == null ? null : expected.toString());
}
}
Then use "with" in my Expectation.
try {
port.createResource(with(req, new BusinessMethodRequestMatcher(req)));
returns(resp);
}
The mock object now recognises the business method call with the correct parameter and returns the expected response object.

LinkedIn Connections List code is Required for android application

I am new In android and currently working on a project which shows different friend list of different social network.
But Here at the stage I am fail to get LinkedIn Connections List and I have searched rest of the Internet but couldn't find any way. . .
If anyone know the code please help me. . . thanks in advance. .
Cheer!
Sample code is here Bellow. . .
final LinkedInOAuthService oAuthService = LinkedInOAuthServiceFactory
.getInstance().createLinkedInOAuthService(
Config.LINKEDIN_CONSUMER_KEY,Config.LINKEDIN_CONSUMER_SECRET, Config.scopeParams);
final LinkedInApiClientFactory factory = LinkedInApiClientFactory
.newInstance(Config.LINKEDIN_CONSUMER_KEY,
Config.LINKEDIN_CONSUMER_SECRET);
LinkedInRequestToken liToken;
LinkedInApiClient client;
LinkedInAccessToken accessToken = null;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if( Build.VERSION.SDK_INT >= 9){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
share = (Button) findViewById(R.id.share);
name = (TextView) findViewById(R.id.name);
et = (EditText) findViewById(R.id.et_share);
login = (Button) findViewById(R.id.login);
photo = (ImageView) findViewById(R.id.photo);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
linkedInLogin();
}
});
// share on linkedin
share.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String share = et.getText().toString();
if (null != share && !share.equalsIgnoreCase("")) {
OAuthConsumer consumer = new CommonsHttpOAuthConsumer(Config.LINKEDIN_CONSUMER_KEY, Config.LINKEDIN_CONSUMER_SECRET);
consumer.setTokenWithSecret(accessToken.getToken(), accessToken.getTokenSecret());
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost("https://api.linkedin.com/v1/people/~/shares");
try {
consumer.sign(post);
} catch (OAuthMessageSignerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthCommunicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // here need the consumer for sign in for post the share
post.setHeader("content-type", "text/XML");
String myEntity = "<share><comment>"+ share +"</comment><visibility><code>anyone</code></visibility></share>";
try {
post.setEntity(new StringEntity(myEntity));
org.apache.http.HttpResponse response = httpclient.execute(post);
Toast.makeText(LinkedInSampleActivity.this,
"Shared sucessfully", Toast.LENGTH_SHORT).show();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
Toast.makeText(LinkedInSampleActivity.this,
"Please enter the text to share",
Toast.LENGTH_SHORT).show();
}
/*String share = et.getText().toString();
if (null != share && !share.equalsIgnoreCase("")) {
client = factory.createLinkedInApiClient(accessToken);
client.postNetworkUpdate(share);
et.setText("");
Toast.makeText(LinkedInSampleActivity.this,
"Shared sucessfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(LinkedInSampleActivity.this,
"Please enter the text to share",
Toast.LENGTH_SHORT).show();
}*/
}
});
}
private void linkedInLogin() {
ProgressDialog progressDialog = new ProgressDialog(
LinkedInSampleActivity.this);
LinkedinDialog d = new LinkedinDialog(LinkedInSampleActivity.this,
progressDialog);
d.show();
// set call back listener to get oauth_verifier value
d.setVerifierListener(new OnVerifyListener() {
#Override
public void onVerify(String verifier) {
try {
Log.i("LinkedinSample", "verifier: " + verifier);
accessToken = LinkedinDialog.oAuthService
.getOAuthAccessToken(LinkedinDialog.liToken,
verifier);
LinkedinDialog.factory.createLinkedInApiClient(accessToken);
client = factory.createLinkedInApiClient(accessToken);
// client.postNetworkUpdate("Testing by Mukesh!!! LinkedIn wall post from Android app");
Log.i("LinkedinSample",
"ln_access_token: " + accessToken.getToken());
Log.i("LinkedinSample",
"ln_access_token: " + accessToken.getTokenSecret());
Person p = client.getProfileForCurrentUser();
name.setText("Welcome " + p.getFirstName() + " "
+ p.getLastName());
name.setVisibility(0);
login.setVisibility(4);
share.setVisibility(0);
et.setVisibility(0);
} catch (Exception e) {
Log.i("LinkedinSample", "error to get verifier");
e.printStackTrace();
}
}
});
// set progress dialog
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(true);
progressDialog.show();
}
}
try this get user-Connections
public class LinkCon_Main extends BaseActivityListView {
final LinkedInOAuthService oAuthService = LinkedInOAuthServiceFactory
.getInstance().createLinkedInOAuthService(Config.CONSUMER_KEY,
Config.CONSUMER_SECRET);
final LinkedInApiClientFactory factory = LinkedInApiClientFactory
.newInstance(Config.CONSUMER_KEY, Config.CONSUMER_SECRET);
ProgressDialog mPrograss;
String name;
View experiencePage;
TextView prof_Name, prof_Headline, prof_Location, prof_Industry;
String prof_name, prof_headline, prof_location, prof_industry, prof_summary, prof_experience,prof_education,prof_languages,prof_skills, prof_interests,prof_birthdate,prof_contatct,prof_email;
String con_name, con_headline, con_location,con_industry, con_summary,con_experience,con_education,con_languages,con_skills,con_interets,con_birthdate,con_phone;
Connections con_email;
String pic_url,con_pic_url;
String startDate, endDate;
String item;
String dty;
String dtm;
String dtd;
ImageView person_Pic, con_pic;
Map<SearchParameter, String> searchParameters;
ListView connections_list;
ArrayList<Person> itemslist;
#SuppressWarnings({ "rawtypes" })
Iterator localIterator;
Person mylist;
RelativeLayout layout_persondetils,layout_con_profile;
LinkedInApiClient client;
Person person;
Connections connections;
ImageLoader imageLoader;
DisplayImageOptions options;
LinkConApp myLinkCon;
LayoutInflater inflater;
String[] months= {"Jan", "Feb", "March", "April", "May","June", "July", "August","Sep", "Oct", "Nov", "Dec"};
StringBuilder localStringBuilder;
#Override
#SuppressLint("NewApi")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myLinkCon=new LinkConApp();
prof_Name=(TextView)findViewById(R.id.user_name);
prof_Headline=(TextView)findViewById(R.id.user_headline);
prof_Location=(TextView)findViewById(R.id.user_Location);
prof_Industry=(TextView)findViewById(R.id.user_industry);
person_Pic=(ImageView)findViewById(R.id.profile_pic);
layout_persondetils=(RelativeLayout)findViewById(R.id.layout_profiledetils);
layout_con_profile=(RelativeLayout)findViewById(R.id.layout_con_profile);
layout_persondetils.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
userpersons();
}
});
mPrograss=new ProgressDialog(LinkCon_Main.this);
inflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// ImageLoader options
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_launcher)
.showImageForEmptyUri(R.drawable.photo)
.showImageOnFail(R.drawable.ic_launcher).cacheInMemory(true)
.cacheOnDisc(true).considerExifParams(true).build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(this));
connections_list=(ListView)findViewById(R.id.connectionslist);
itemslist = new ArrayList<Person>();
if( Build.VERSION.SDK_INT >= 9){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
final SharedPreferences pref = getSharedPreferences(Config.OAUTH_PREF,
MODE_PRIVATE);
final String token = pref.getString(Config.PREF_TOKEN, null);
final String tokenSecret = pref.getString(Config.PREF_TOKENSECRET, null);
if (token == null || tokenSecret == null) {
startAutheniticate();
} else {
showCurrentUser(new LinkedInAccessToken(token, tokenSecret));
}
}
void startAutheniticate() {
mPrograss.setMessage("Loading...");
mPrograss.setCancelable(true);
mPrograss.show();
new AsyncTask<Void, Void, LinkedInRequestToken>() {
#Override
protected LinkedInRequestToken doInBackground(Void... params) {
return oAuthService.getOAuthRequestToken(Config.OAUTH_CALLBACK_URL);
}
#Override
protected void onPostExecute(LinkedInRequestToken liToken) {
final String uri = liToken.getAuthorizationUrl();
getSharedPreferences(Config.OAUTH_PREF, MODE_PRIVATE)
.edit()
.putString(Config.PREF_REQTOKENSECRET,
liToken.getTokenSecret()).commit();
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(i);
}
}.execute();
mPrograss.dismiss();
}
void finishAuthenticate(final Uri uri) {
if (uri != null && uri.getScheme().equals(Config.OAUTH_CALLBACK_SCHEME)) {
final String problem = uri.getQueryParameter(Config.OAUTH_QUERY_PROBLEM);
if (problem == null) {
new AsyncTask<Void, Void, LinkedInAccessToken>() {
#Override
protected LinkedInAccessToken doInBackground(Void... params) {
final SharedPreferences pref = getSharedPreferences(
Config.OAUTH_PREF, MODE_PRIVATE);
final LinkedInAccessToken accessToken = oAuthService
.getOAuthAccessToken(
new LinkedInRequestToken(
uri.getQueryParameter(Config.OAUTH_QUERY_TOKEN),
pref.getString(
Config.PREF_REQTOKENSECRET,
null)),
uri.getQueryParameter(Config.OAUTH_QUERY_VERIFIER));
pref.edit()
.putString(Config.PREF_TOKEN, accessToken.getToken())
.putString(Config.PREF_TOKENSECRET,
accessToken.getTokenSecret())
.remove(Config.PREF_REQTOKENSECRET).commit();
return accessToken;
}
#Override
protected void onPostExecute(LinkedInAccessToken accessToken) {
mPrograss.dismiss();
showCurrentUser(accessToken);
}
}.execute();
} else {
Toast.makeText(this,
"Appliaction down due OAuth problem: " + problem,
Toast.LENGTH_LONG).show();
finish();
}
}
}
void clearTokens() {
getSharedPreferences(Config.OAUTH_PREF, MODE_PRIVATE).edit()
.remove(Config.PREF_TOKEN).remove(Config.PREF_TOKENSECRET)
.remove(Config.PREF_REQTOKENSECRET).commit();
}
void showCurrentUser(final LinkedInAccessToken accessToken) {
client = factory.createLinkedInApiClient(accessToken);
mPrograss.setMessage("Loading..");
mPrograss.show();
new AsyncTask<Void, Void, Object>() {
#Override
protected Object doInBackground(Void... params) {
try {
final Person user_Profile = client.getProfileForCurrentUser(EnumSet.of(ProfileField.ID));
person = client.getProfileById(user_Profile.getId(), EnumSet.of(
ProfileField.FIRST_NAME,
ProfileField.LAST_NAME,
ProfileField.PICTURE_URL,
ProfileField.INDUSTRY,
ProfileField.MAIN_ADDRESS,
ProfileField.HEADLINE,
ProfileField.SUMMARY,
ProfileField.POSITIONS,
ProfileField.EDUCATIONS,
ProfileField.LANGUAGES,
ProfileField.SKILLS,
ProfileField.INTERESTS,
ProfileField.PHONE_NUMBERS,
ProfileField.EMAIL_ADDRESS,
ProfileField.DATE_OF_BIRTH,
ProfileField.PUBLIC_PROFILE_URL));
prof_name = person.getFirstName() + " " + person.getLastName();
prof_headline = person.getHeadline();
prof_location = person.getMainAddress();
prof_industry = person.getIndustry();
return person;
} catch (LinkedInApiClientException ex) {
return ex;
}
}
#Override
protected void onPostExecute(Object result) {
if (result instanceof Exception) {
//result is an Exception :)
final Exception ex = (Exception) result;
clearTokens();
Toast.makeText(
LinkCon_Main.this,
"Appliaction down due LinkedInApiClientException: "
+ ex.getMessage()
+ " Authokens cleared - try run application again.",
Toast.LENGTH_LONG).show();
finish();
} else if (result instanceof Person) {
final Person person = (Person) result;
prof_Name.setText( person.getFirstName() + " " + person.getLastName());
prof_Headline.setText(person.getHeadline());
prof_Location.setText(person.getMainAddress());
prof_Industry.setText(person.getIndustry());
prof_Name.setVisibility(0);
prof_Headline.setVisibility(0);
prof_Location.setVisibility(0);
prof_Industry.setVisibility(0);
person_Pic.setVisibility(0);
userConnections();
userDetails();
}
}
}.execute();
mPrograss.dismiss();
}
#Override
protected void onNewIntent(Intent intent) {
finishAuthenticate(intent.getData());
}
public void userDetails(){
if(person.getPictureUrl()!=null){
pic_url = person.getPictureUrl().toString();
imageLoader.displayImage(pic_url, person_Pic);
}else{
person_Pic.setImageResource(R.drawable.ic_launcher);
}
/*************** person Details Summary/experience/education/languages/skills/contacts/interests **********************/
if (person.getSummary()!=null) {
prof_summary = person.getSummary();
}
prof_experience="";
for (Position position:person.getPositions().getPositionList())
{
if(position.isIsCurrent()){
startDate=months[(int) (position.getStartDate().getMonth()-1)]+"-"+position.getStartDate().getYear();
endDate="Currently Working";
}else{
startDate=months[(int) (position.getStartDate().getMonth()-1)]+"-"+position.getStartDate().getYear();
endDate=months[(int) (position.getEndDate().getMonth()-1)]+"-"+position.getEndDate().getYear();
}
prof_experience=prof_experience+"<b>" +"Position :"+"</b>"+position.getTitle()+"<br><b>" +"Company :"+ "</b>"+ position.getCompany().getName()+"<br><b>" +"Start Date:"+ "</b>"+ startDate +"<br><b>" +"End Date:"+ "</b>"+ endDate +"<br>"+"<br>";
}
prof_education="";
for (Education education:person.getEducations().getEducationList())
{
prof_education=prof_education +"<b>" +"Gaduation :"+ "</b>" +education.getDegree()+"<br><b>" +"Institute :"+ "</b>" +education.getSchoolName()+ "<br><b>" +"Graduation Year :"+ "</b>" +education.getEndDate().getYear()+"<br>"+"<br>";
}
prof_languages="";
for(Language language:person.getLanguages().getLanguageList())
{
prof_languages=prof_languages+language.getLanguage().getName()+"\n";
}
prof_skills="";
for(Skill skill:person.getSkills().getSkillList())
{
prof_skills=prof_skills+skill.getSkill().getName()+"\n";
}
prof_contatct="";
PhoneNumbers contactinfo=person.getPhoneNumbers();
if(contactinfo!=null ){
for(PhoneNumber phoneno:person.getPhoneNumbers().getPhoneNumberList())
{
prof_contatct=prof_contatct+ phoneno.getPhoneNumber().toString();
}
}
if(person.getEmailAddress()!=null){
prof_email=person.getEmailAddress();
}
prof_interests = person.getInterests();
prof_birthdate= person.getDateOfBirth().getDay()+"-"+ months[(int) (person.getDateOfBirth().getMonth()-1)]+"-"+person.getDateOfBirth().getYear();
}
public void userConnections(){
final Set<ProfileField> connectionFields = EnumSet.of(ProfileField.ID,
ProfileField.FIRST_NAME,
ProfileField.LAST_NAME,
ProfileField.HEADLINE,
ProfileField.INDUSTRY,
ProfileField.PICTURE_URL,
ProfileField.MAIN_ADDRESS,
ProfileField.LOCATION,
ProfileField.LOCATION_COUNTRY,
ProfileField.LOCATION_NAME,
ProfileField.SUMMARY,
ProfileField.EDUCATIONS,
ProfileField.EDUCATIONS_DEGREE,
ProfileField.EDUCATIONS_END_DATE,
ProfileField.EDUCATIONS_FIELD_OF_STUDY,
ProfileField.EDUCATIONS_ID,
ProfileField.EDUCATIONS_SCHOOL_NAME,
ProfileField.EDUCATIONS_START_DATE,
ProfileField.LANGUAGES,
ProfileField.LANGUAGES_ID,
ProfileField.LANGUAGES_LANGUAGE,
ProfileField.LANGUAGES_LANGUAGE_NAME,
ProfileField.POSITIONS,
ProfileField.POSITIONS_COMPANY,
ProfileField.POSITIONS_COMPANY_INDUSTRY,
ProfileField.POSITIONS_COMPANY_NAME,
ProfileField.POSITIONS_END_DATE,
ProfileField.POSITIONS_IS_CURRENT,
ProfileField.POSITIONS_START_DATE,
ProfileField.POSITIONS_SUMMARY,
ProfileField.POSITIONS_TITLE,
ProfileField.SKILLS,
ProfileField.INTERESTS,
ProfileField.PHONE_NUMBERS,
ProfileField.EMAIL_ADDRESS,
ProfileField.DATE_OF_BIRTH,
ProfileField.PUBLIC_PROFILE_URL
);
connections = client.getConnectionsForCurrentUser(connectionFields);
for (Person person : connections.getPersonList()) {
itemslist.add(person);
}
connection_Adapter myadpter=new connection_Adapter();
connections_list.setAdapter(myadpter);
connections_list.setVisibility(0);
connections_list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/*Connections List item position selection*/
person = itemslist.get(position);
/*
Map<SearchParameter, String> searchParameters = new EnumMap<SearchParameter, String>(SearchParameter.class);
searchParameters.put(SearchParameter.KEYWORDS, "University of X");
People people = client.searchPeople(searchParameters);
System.out.println("Total search result:" + people.getCount());
for (Person person : people.getPersonList()) {
System.out.println(person.getId() + ":" + person.getFirstName() + " " +
person.getLastName() + ":" + person.getHeadline());
}*/
/*
People people = client.searchPeople(searchParameters);
for (Person persons : people.getPersonList()) {
persons = client.getProfileByApiRequest(persons.getApiStandardProfileRequest());
}
Log.i("My Persons list", ""+person);*/
/*Intent mycon=new Intent(LinkCon_Main.this, Con_Profile.class);
mycon.putExtra("conid", con_name);
startActivity(mycon);
*/
con_name=person.getFirstName()+" "+person.getLastName();
System.out.println("Name:"+con_name);
con_headline=person.getHeadline();
System.out.println("Designation:"+con_headline);
con_industry=person.getIndustry();
System.out.println("Industry:"+con_industry);
Location localLocation = person.getLocation();
if (localLocation != null){
con_location=String.format("%s", new Object[] { localLocation.getName() });
System.out.println("Con_Loaction:"+con_location);
}
/*****PICTURE/NAME/INDUSTRY/LOCATION Tested OK******/
/********need to get SUMMARY/EXPERIENCE/EDUCATION/SKILLS/LANGUAGES/DATEOFBIRTH/PHONENUMBER/EMAIL**********/
Toast.makeText(LinkCon_Main.this, "Name:"+" "+con_name +"\n"+"Position:"+" "+con_headline+"\n"+"Industry:"+" "+con_industry+"\n"+"Locations:"+" "+con_location, Toast.LENGTH_LONG).show();
}//onItemClick
});
}
public class connection_Adapter extends BaseAdapter{
#Override
public int getCount() {
// TODO Auto-generated method stub
return itemslist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder = null;
if(convertView==null){
convertView = inflater.inflate(R.layout.list_row,
null);
holder = new ViewHolder();
holder.con_Itenames = (TextView) convertView
.findViewById(R.id.connection_name);
holder.con_designations = (TextView) convertView
.findViewById(R.id.connection_headline);
holder.con_ItemImage = (ImageView) convertView
.findViewById(R.id.connection_image);
holder.con_locationad = (TextView) convertView
.findViewById(R.id.connection_location);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
SetData(holder,position);
return convertView;
}
protected Context getBaseContext() {
// TODO Auto-generated method stub
return null;
}
public void SetData(final ViewHolder holder, int position) {
final Person con_details = itemslist.get(position);
holder.con_Itenames.setText(con_details.getFirstName()+" "+con_details.getLastName());
holder.con_designations.setText(con_details.getIndustry());
Location localLocation = con_details.getLocation();
if (localLocation != null){
con_location=String.format("%s", new Object[] { localLocation.getName() });
}
holder.con_locationad.setText(con_location);
holder.con_Itenames.setTag(con_details);
if (con_details.getPictureUrl()!=null) {
imageLoader.displayImage(con_details.getPictureUrl(), holder.con_ItemImage, options);
}else {
holder.con_ItemImage.setImageResource(R.drawable.ic_launcher);}
}
public void setListItems(ArrayList<Person> newList) {
itemslist = newList;
notifyDataSetChanged();
}
}
public class ViewHolder{
TextView con_Itenames,con_designations, con_locationad;
ImageView con_ItemImage;
}
private void userpersons() {
// TODO Auto-generated method stub
Intent user_prof = new Intent(LinkCon_Main.this, User_Profile.class);
user_prof.putExtra("pic", pic_url);
user_prof.putExtra("name", prof_name);
user_prof.putExtra("headline", prof_headline);
user_prof.putExtra("locations", prof_location);
user_prof.putExtra("industry", prof_industry);
user_prof.putExtra("summary", prof_summary);
user_prof.putExtra("languages", prof_languages);
user_prof.putExtra("experience", prof_experience);
user_prof.putExtra("education", prof_education);
user_prof.putExtra("skills", prof_skills);
user_prof.putExtra("interests", prof_interests);
user_prof.putExtra("dateofbirth", prof_birthdate);
user_prof.putExtra("phoneno", prof_contatct);
user_prof.putExtra("email", prof_email);
startActivity(user_prof);
}
}

Obtain List from asynctask

public class GetAllEggs extends AsyncTask<Void, Void, List<Egg>> {
List<Egg> eggs;
Egg eg;
JSONParser jParser = new JSONParser();
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<Egg> doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
// Thread.sleep(5000);
/*** fetch data from server and save in the local db ***/
String url = Utils.alleggsofuser;
JSONObject jObject = jParser.makeHttpRequest(url, "GET", null);
//Log.d(DEBUG_TAG, "news response: " + response);
JSONArray categoryArray = new JSONArray(
jObject.getString("categories"));
for (int i = 0; i < categoryArray.length(); i++) {
/* make entries in the db */
JSONObject Category = categoryArray.getJSONObject(i);
eg=new Egg();
eg.setEggid(Category.getInt("eggid"));
eg.setApp_user_id(Category.getInt("app_user_id"));
eg.setEgg_query(Category.getString("egg_query"));
eg.setEgg_date_time(null);
eggs.add(eg);
/**/
}
/**/
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// pBar.cancel();
}
return eggs;
}
protected void onPostExecute(List<Egg> result) {
// TODO Auto-generated method stub
}
List<Egg> eggs=new ArrayList();
new GetAllEggs().execute(eggs);
i want eggs to grab data returned by GetAllEggs().execute().
So that i can Use the eggs returned, in another class where it can be displayed.
I am trying to assign the data returned to a list in the new class.
I cannot carry out the operation in postexecute() because of the structure of the program
Instead of passing from post execute to ui thread i can call a ui thread in post execute using
runOnUiThread(new Runnable() { public void run() {}});

uploading file from backberry to web service = JVM error 104 Uncaught NullPointerException?

I am developing a small blackberry project.
Here are the step that it is supposed to be:
User clicks Speak! button. The application record speech voice. [No Problem]
When user finishes speaking, click Stop! button. Once the stop button is clicked, the speech voice will be saved on BB as an AMR file. Then, the file will be sent to web service via ksoap2. Web service will return response as a string of file name. The problem is web service return nothing and there is an error occur: JVM error 104: Uncaught NullPointerException I wonder if I placed the code on the right place, or I did something wrong with ksoap2??
here is the code for web service
namespace VoiceServer
{
/// <summary>
/// Converting AMR to WAV
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class Service1 : System.Web.Services.WebService
{
public string UploadFile(String receivedByte, String location, String fileName)
{
String filepath = fileName;
/*don't worry about receivedByte and location, I will work on them after the problem is solved :) */
return "Success"+filepath;
}
private void InitializeComponent()
{
}
}
}
Below is the code running on Eclipse, I'm not sure if I placed the code for sending file to web service on the right place.
public class MyAudio extends MainScreen {
private ButtonField _startRecordingButton;
private ButtonField _stopRecordingButton;
private HorizontalFieldManager _fieldManagerButtons;
private VoiceNotesRecorderThread _voiceRecorder;
private LabelField _myAudioTextField;
private DateField hourMin;
private long _initTime;
public MyAudio() {
_startRecordingButton = new ButtonField("Speak!", ButtonField.CONSUME_CLICK);
_stopRecordingButton = new ButtonField("Stop!", ButtonField.CONSUME_CLICK);
_fieldManagerButtons = new HorizontalFieldManager();
_voiceRecorder = new VoiceNotesRecorderThread(500000,"file:///store/home/user/voicefile.amr",this);
_voiceRecorder.start();
myButtonFieldChangeListener buttonFieldChangeListener = new myButtonFieldChangeListener();
_startRecordingButton.setChangeListener(buttonFieldChangeListener);
_stopRecordingButton.setChangeListener(buttonFieldChangeListener);
_fieldManagerButtons.add(_startRecordingButton);
_fieldManagerButtons.add(_stopRecordingButton);
_myAudioTextField = new LabelField(" Welcome to VoiceSMS!!!" );
add(_fieldManagerButtons);
add(_myAudioTextField);
SimpleDateFormat sdF = new SimpleDateFormat("ss");
hourMin = new DateField("", 0, sdF);
hourMin.setEditable(false);
hourMin.select(false);
_initTime = System.currentTimeMillis();
add(hourMin);
}
public void setAudioTextField(String text) {
_myAudioTextField.setText(text);
}
public void startTime() {
_initTime = System.currentTimeMillis();
hourMin.setDate(0);
}
public void updateTime() {
hourMin.setDate((System.currentTimeMillis()-_initTime));
}
class myButtonFieldChangeListener implements FieldChangeListener{
public void fieldChanged(Field field, int context) {
if(field == _startRecordingButton) {
try {
_voiceRecorder.startRecording();
} catch (IOException e) {
e.printStackTrace();
}
}else if(field == _stopRecordingButton) {
_voiceRecorder.stopRecording();
//----------Send AMR to Web Service-------------//
Object response = null;
String URL = "http://http://localhost:portnumber/Service1.asmx";
String method = "UploadFile";
String NameSpace = "http://tempuri.org/";
FileConnection fc = null;
byte [] ary = null;
try
{
fc = (FileConnection)Connector.open("file:///store/home/user/voicefile.amr",Connector.READ_WRITE);
int size = (int) fc.fileSize();
//String a = Integer.toString(size);
//Dialog.alert(a);
ary = new byte[size];
fc.openDataInputStream().read(ary);
fc.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
SoapObject client = new SoapObject(NameSpace,method);
client.addProperty("receivedByte",new SoapPrimitive(SoapEnvelope.ENC,"base64",Base64.encode(ary)));
client.addProperty("location","Test/");
client.addProperty("fileName","file:///store/home/user/voicefile.amr");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut = client;
HttpTransport http = new HttpTransport(URL);
try
{
http.call(method,envelope);
}
catch(InterruptedIOException io)
{
io.printStackTrace();
}
catch (IOException e)
{
System.err.println(e);
}
catch (XmlPullParserException e)
{
System.err.println(e);
}
catch(OutOfMemoryError e)
{
System.out.println(e.getMessage());
}
catch(Exception e)
{
e.printStackTrace();
}
try
{
response = envelope.getResponse();
Dialog.alert(response.toString());
}
catch (SoapFault e)
{
System.err.println(e);
System.out.println("Soap Fault");
}
catch(NullPointerException ne)
{
System.err.println(ne);
}
Dialog.alert(response.toString());
//Dialog.alert("Send Success");
//----------End of Upload-to-Web-Service--------//
}
}
}
}
I don't know if the file is not sent to web service, or web service has got the file and produce no response??? I am a real newbie for BB programming. Please let me know if I did anything wrong.
Thanks in advance!!!
There is a typo in your URL variable value.
"http://" typed twice
String URL = "http://http://localhost:portnumber/Service1.asmx";
Hooray!!! Problem Solved!
just changed URL as Rafael suggested and added [WebMethod] above "public string UploadFile" in the web service code