I am fairly new to android programming and I have faced a small problem. I have an arraylist consisting of names of person selected from a multi-select listview, the problem is that Whenever I insert those arraylist values into the database, It inserts it as one string:
Database row. How do i iterate thru an arraylist and at the same time insert its values into the database?
here is my code:
try {
Connection con = connectionClass.CONN();
if (con == null) {
Toast.makeText(getApplicationContext(), "CONNECTION FAIL", Toast.LENGTH_LONG).show();
} else {
String samp = "";
String names = "";
samp = myArrayAdapter.getCheckedItems().toString();
ArrayList<String> data1 = new ArrayList<String>();
data1.add(samp);
for(int x=0; x<data1.size(); x++)
{
names += String.valueOf(data1.get(x));
String query = "INSERT INTO AUTOINC(PersonName)"+"VALUES('"+names+"')";
PreparedStatement preparedStatement = con.prepareStatement(query);
preparedStatement.executeUpdate();
}
Toast.makeText(getApplicationContext(), "INSERT SUCCESS", Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "INSERT FAILED", Toast.LENGTH_LONG).show();
Log.e("MYAPP", "exception", ex);
}
Thank you for any future replies.
Can you try with that?
List<String> data1 = new ArrayList<String>(Arrays.asList(samp.replace("[","").replace("]","").split(",")));
for (String name : data1) {
names += name; // This lines concatenate the name.
//If you want to insert single name the you can directly insert the name value into databas.
String query = "INSERT INTO AUTOINC(PersonName)"+"VALUES('"+name+"')";
PreparedStatement preparedStatement = con.prepareStatement(query);
preparedStatement.executeUpdate();
}
look at this code...
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
PropertyInfo pi=new PropertyInfo();
pi.setName("UserName");
pi.setValue(txtName.getText().toString());
pi.setType(String.class);
request.addProperty(pi);
pi=new PropertyInfo();
pi.setName("UserAge");
pi.setValue(txtVal.getText().toString());
pi.setType(String.class);
request.addProperty(pi);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(webRequest);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION + METHOD_NAME, envelope);
Log.d("CheckLogin-SOAP ACTION", SOAP_ACTION + METHOD_NAME);
SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
Log.d("CheckLogin - Response", response.toString());
status= Boolean.valueOf(response.toString());
Related
I am having some problem when trying to access MySQL from Android via Servlet. What I am trying to do is check if the event exist in database by passing some value to servlet class. If no existing record, then perform DB insertion.
public void createEvent(Event event) {
String page;
JSONArray jsonArray;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(ENeighbourhoodActivity.URL + "checkEventExist");
List<NameValuePair> checkExistnvp = new ArrayList<NameValuePair>(3);
checkExistnvp.add(new BasicNameValuePair("eventName", event.getEventName()));
checkExistnvp.add(new BasicNameValuePair("eventX", event.getEventX()));
checkExistnvp.add(new BasicNameValuePair("eventY", event.getEventY()));
try {
post.setEntity(new UrlEncodedFormEntity(checkExistnvp));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
page = "{\'Events\':" + responseString + "}";
try {
JSONObject jsonObject = new JSONObject(page);
jsonArray = jsonObject.getJSONArray("Events");
int length = jsonArray.length();
if(length == 0){
// If no existing record, then perform DB insertion
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
And inside my servlet:
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
JSONArray jsonArray = new JSONArray();
PrintWriter out = response.getWriter();
if (request.getParameter("checkEventExist") != null) {
String eventX = request.getParameter("eventX");
String eventY = request.getParameter("eventY");
String eventName = request.getParameter("eventName");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost/mydb", "root", "root");
PreparedStatement statement = con
.prepareStatement("SELECT * FROM event WHERE eventName = '" + eventName + "' AND eventX = '" + eventX + "' AND eventY = '"+ eventY + "'");
ResultSet result = statement.executeQuery();
while (result.next()) {
JSONObject eventInfo = new JSONObject();
eventInfo.put("eventName", result.getString("eventName"));
eventInfo.put("eventX", result.getString("eventX"));
eventInfo.put("eventY", result.getString("eventY"));
jsonArray.put(eventInfo);
}
}
catch (JSONException je) {
System.out.println(je.getMessage());
} catch (Exception exc) {
System.out.println(exc.getMessage());
}
out.println(jsonArray.toString());
}
}
I not sure how should I pass and get name/value pairs into the doGet() in servlet. With this line:
post.setEntity(new UrlEncodedFormEntity(checkExistnvp));
It's how I pass value into the doPost(). But I need to pass it to doGet() instead. Any guides?
Thanks in advance.
You should use query parameters since HTTP GET does not allow sending entity in HTTP Body.
In order to send parameters for the HTTP GET, you should prepare a URL like this:
HttpGet request = new HttpGet(ENeighbourhoodActivity.URL + "checkEventExist?" +
"eventName=<eventName>&"+
"eventX=<eventX>&"+
"eventY=<eventY>");
HttpResponse response = client.execute(request);
And you shouldn't add any NameValuePair to the request
i am trying to set up connection to SOAP WebService from Android app but every time i get wried error in my result :
object reference not set to an instance of an object java
It seems to be error from server --> SOAP Webservice call from Java gives "Object reference not set to an instance of an object"
But when i try it throught web browser with POST request it works fine :)
This service http://ws.cdyne.com/ip2geo/ip2geo.asmx?op=ResolveIP
private static String NAMESPACE = "http://ws.cdyne.com/";
private static String URL = "http://ws.cdyne.com/ip2geo/ip2geo.asmx";
private static String SOAP_ACTION = "http://ws.cdyne.com/";
public static String invokeHelloWorldWS(String name, String webMethName) {
String resTxt = null;
SoapObject request = new SoapObject(NAMESPACE, webMethName);
PropertyInfo sayHelloPI = new PropertyInfo();
// Set name
sayHelloPI.setName("ipAddress");
// Set Value
sayHelloPI.setValue("88.212.35.129");
// Set dataType
sayHelloPI.setType(String.class);
// Add the property to request object
request.addProperty(sayHelloPI);
// Create envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
// Set output SOAP object
envelope.setOutputSoapObject(request);
// Create HTTP call object
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.debug = true;
try{
// Invoke web service
androidHttpTransport.call(SOAP_ACTION+webMethName, envelope); //webMethName = "ResolveIP"
// Get the response
Log.d("a", androidHttpTransport.responseDump);
//SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
// Assign it to resTxt variable static variable
//resTxt = response.toString();
}catch(Exception e){
//Print error
e.printStackTrace();
}
}
I spend lot of time on google but i cant figure right answer why this happend
// EDIT
Finally i get it right ... idk why but when i send second parameter like this (i reuse old property) :
sayHelloPI.setName("licenseKey");
sayHelloPI.setValue("some_key");
sayHelloPI.setType(String.class);
request.addProperty(sayHelloPI);
it wasnt working. But when i make new Property object it works:
PropertyInfo sayHelloPI1 = new PropertyInfo();
sayHelloPI1.setName("licenseKey");
sayHelloPI1.setValue("ds");
sayHelloPI1.setType(String.class);
request.addProperty(sayHelloPI1);
Maybe it help someone next time
This is some code that I have used myself - Hope it will help you:
// Initialize soap request + add parameters
SoapObject request = new SoapObject(getString(R.string.Namespace),
getString(R.string.Method_Name_GetStudentsByTeam));
Log.d("GetStudentsByTeamTask", "SOAP request");
// Use this to add parameters
request.addProperty("teamId", params[0]);
Log.d("GetStudentsByTeamTask", "id: " + params[0]);
// Declare the version of the SOAP request
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
Log.d("GetStudentsByTeamTask",
"Declared the version of the SOAP request");
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
Log.d("GetStudentsByTeamTask", "Setting som variables");
try {
HttpTransportSE androidHttpTransport = new HttpTransportSE(
getString(R.string.URL));
Log.d("GetStudentsByTeamTask", "Instance the HttpTransportSE");
// this is the actual part that will call the webservice
androidHttpTransport.call(
getString(R.string.Soap_Action_GetStudentsByTeam),
envelope);
Log.d("GetStudentsByTeamTask", "Called the Webservice");
// Get the SoapResult from the envelope body.
SoapObject result = (SoapObject) envelope.getResponse();
Log.d("GetStudentsByTeamTask", "Got the Soapresult");
if (result != null) {
// Do something with result
// success = true;
Log.d("GetStudentsByTeamTask", "set sucess boolean to true");
for (int i = 0; i < result.getPropertyCount(); i++) {
PropertyInfo pi = new PropertyInfo();
result.getPropertyInfo(i, pi);
Log.d("GetStudentsByTeamTask",
pi.name + " : " + result.getProperty(i));
SoapObject obj = (SoapObject) result.getProperty(i);
Student student = new Student();
student.address = obj.getProperty("Address").toString();
student.city = obj.getProperty("City").toString();
student.created = DateTime.parse(obj.getProperty(
"Created").toString());
student.dateOfBirth = DateTime.parse(obj.getProperty(
"DateOfBirth").toString());
student.email = obj.getProperty("Email").toString();
student.firstname = obj.getProperty("FirstName")
.toString();
student.id = Integer.parseInt(obj.getProperty("ID")
.toString());
student.imageId = Integer.parseInt(obj.getProperty(
"ImageID").toString());
// SoapObject lastNameObject = (SoapObject) obj
// .getProperty("LastName");
//
student.lastName = obj.getProperty("LastName")
.toString();
student.phone = obj.getProperty("Mobile").toString();
student.zipcode = obj.getProperty("PostalCode")
.toString();
student.schoolId = Integer.parseInt(obj
.getPropertyAsString("SchoolId"));
student.teamId = Integer.parseInt(obj
.getPropertyAsString("TeamId"));
student.testStarted = Integer.parseInt(obj
.getPropertyAsString("TestsStarted"));
student.timeStamp = DateTime.parse(obj
.getPropertyAsString("TimeStamp"));
student.image = getImage(Integer.parseInt(obj
.getProperty("ImageID").toString()));
if (student.image == null)
student.image = BitmapFactory
.decodeResource(getResources(),
R.drawable.default_usericon);
MyApp.getController().addStudent(student);
}
} else {
// If fails
// success = false;
Log.d("GetStudentsByTeamTask", "set login boolean to false");
}
} catch (Exception e) {
Log.d("GetStudentsByTeamTask", "FAILED! " + e.getMessage());
e.printStackTrace();
}
I am using KSOAP2 to call a Axis 2 webservice from android application,and the response from the web service is in the following format:
[Book{id=1; name=C++ for Begginers; Author=Martin;},Book{id=2; name=Java Development; Author=Charles;},Book{id=3; name=Android Guide; Author=Sam};]
The code for Axis 2 Web service class is as following:
public class Book_Web_Service {
private String url;
private Connection con;
private Statement stmt;
public void connectToDB() {
url = "jdbc:mysql://localhost:3306/book";
try {
Class.forName("com.mysql.jdbc.Driver");
con = (Connection) DriverManager.getConnection(url, "root", "");
} catch (Exception e) {
System.out.println("Error - Unable to Connect to the Database" + e);
}
}
public ArrayList<Book> getBooksData() {
ArrayList<Book> booklist = new ArrayList<Book>();
connectToDB();
try {
stmt = (Statement) con.createStatement();
String query ="SELECT * from book ";
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
Book b = new Book();
b.setId(rs.getString("id"));
b.setName(rs.getString("name"));
b.setAuthor(rs.getString("author"));
booklist.add(b);
}
}
catch (SQLException e) {
System.out.println("Error - Unable to get books data ......" + e);
}
return booklist;
}
}
The code for getting response in android is this:
ArrayList<Book> booklist = new ArrayList<Book>();
METHOD_NAME = "getBooksData";
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
Object result = envelope.getResponse();
// SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
String response = result.toString();
((TextView) findViewById(R.id.booktxt)).setText("Response:"+ response);
} catch (Exception E) {
E.printStackTrace();
((TextView) findViewById(R.id.booktxt)).setText("ERROR:"
+ E.getClass().getName() + ":" + E.getMessage());
}
I want the response again be in arraylist. So that I can show it in list view. But I am not getting it. Is there any android library which can do this or any easy way to do it????
I have some contact numbers saved in a remote server and I have more than 100 numbers saved on my Android phone.
What I want to do is compare the numbers present on the remote server and the phone numbers in the Android phone and display only the matching numbers in a Listview i.e if 1234 is saved on my remote server and 1234, 5678,1000,etc are saved on my Android phone, then only the number 1234 should be displayed on the Listview.
I have done the following coding and it works fine and gives me the result i want, but the problem is that the time consumption is very high.
Can anyone suggest me whether it is possible to get the matching contacts without using a loop or is there any way to reduce the time consumption?
My codes are as below, please guide me step by step.
AsyncTask<Void, Void,Void> t = new AsyncTask<Void, Void,Void>()
{
#Override
protected Void doInBackground(Void... arg0) {
String phoneNumber = null;
//String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
StringBuffer output = new StringBuffer();
if(getActivity()!=null)
{
ContentResolver contentResolver =getActivity().getApplicationContext().getContentResolver();
//contentResolver=getActivity().getContentResolver().getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null,null, null, null);
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String contact_id = cursor.getString(cursor.getColumnIndex( _ID ));
String name = cursor.getString(cursor.getColumnIndex( DISPLAY_NAME ));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex( HAS_PHONE_NUMBER )));
output.append("\n First Name:" + name);
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[] { contact_id }, null);
while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
String p=phoneNumber;
output.append("\n Phone number:" + phoneNumber);
String result = null;
InputStream is = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2:80/contactcheck.php");
HttpResponse response1 = httpclient.execute(httppost);
HttpEntity entity = response1.getEntity();
is = entity.getContent();
Log.e("log_tag", "connection success ");
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection "+e.toString());
}
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,HTTP.UTF_8),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
try
{
JSONArray jArray = new JSONArray(result);
String s11,s12,s13;
Log.w("Lengh",""+jArray.length());
for(int i=0;i<jArray.length();i++)
{
JSONObject json_data = jArray.getJSONObject(i);
s11=json_data.getString("PhoneId");
s12=json_data.getString("path");
s13=json_data.getString("UserId");
Log.w("matched",""+s11+p);
Log.i("path from json",""+s12);
if(p.compareTo(s11)==0){
int count=0;
count=db.getcountoffriends(s11);
if(count==0)
{
queryValues.put("c",s11);
queryValues.put("name",name);
queryValues.put("path", s12);
queryValues.put("fbid",s13);
db.insertcontact(queryValues);
imageload(s12,s13,s11);
}
Log.i("imageupload strings",""+s12+""+s13+""+s11);
}
}
}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
}
}
return null;
}
};
t.execute();
Take each phone number from remote server and pass to the following method:
public boolean contactExists(Context context, String number) {
/// number is the phone number
Uri lookupUri = Uri.withAppendedPath(
PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(number));
String[] mPhoneNumberProjection = { PhoneLookup._ID, PhoneLookup.NUMBER, PhoneLookup.DISPLAY_NAME };
Cursor cur = context.getContentResolver().query(lookupUri,mPhoneNumberProjection, null, null, null);
try {
if (cur.moveToFirst()) {
return true;
}
} finally {
if (cur != null)
cur.close();
}
return false;
}
If the method returns true, store the relevant data to display in ListView
Original answer Android : Check phone number present in Contact List ? (Phone number retrieve from phone call)
I have android code which has two integers variables getting from HashMap Key , value .
i'm trying to pass these two variables to SOAP web service but nothing happened .
notes 1: I'm sure my WebService code is working and entering the right data to database , i have tested it .
note 2 : FROM debug shows that "SID" and "status" has right values .
but the problem in sending these values to SOAP .
FULL SOAP code in android Activity :
sumbit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for (Map.Entry<Integer, Integer> mapEntry : checkBoxState
.entrySet()) {
int SID = mapEntry.getKey();
int status = mapEntry.getValue();
Toast.makeText(context,
String.valueOf(SID) + String.valueOf(status),
Toast.LENGTH_SHORT).show();
try {
SoapObject request = new SoapObject(NAMESPACE,
METHOD_NAME);
HttpTransportSE androidHttpTransport = new HttpTransportSE(
URL);
PropertyInfo pi = new PropertyInfo();
pi.setName("SID");
pi.setValue(SID);
pi.setType(Integer.class);
request.addProperty(pi);
PropertyInfo pi2 = new PropertyInfo();
pi2.setName("status");
pi2.setValue(status);
pi2.setType(Integer.class);
request.addProperty(pi2);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
androidHttpTransport.call(SOAP_ACTION, envelope);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
FULL webService Method Code :
public void insertApsentData(int SID , int status ) throws SQLException, ClassNotFoundException, ReflectiveOperationException, Throwable{
// Make new Connection to database .
Dbconnection NewConnect = new Dbconnection();
Connection con = NewConnect.MakeConnect();
Statement stmt = con.createStatement();
// this i'm usre is working fine
stmt.executeUpdate("INSERT INTO apsent SET course_id=1, teacher_id= 1 , class_id= 3 , interval_id= 5 , day_id = 1 , APSSENT_DATE = CURdate() ,state = " + status + ", student_id = " + SID +" ,school_id = 1;");//called the procedure
}
I have had this problem before. Have you tried generating the wsdl using eclipse?(see page 6). This tool generates the client code for a webservice and makes it easy to call something like
ServiceProxy.insertApsentData(args)
There is some project Folders are closed , i reopened it and it's works now .