Android Web service #2

37

StudentService.java

package com.example.mywebserivce;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Service;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.IBinder;

public class StudentService extends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
HttpClient hc=new DefaultHttpClient();
HttpGet hg=new HttpGet(
“http://172.16.28.61:8888/Students/getAllStudents”);
try {
HttpResponse hr =hc.execute(hg);
BufferedReader br=new BufferedReader(
new InputStreamReader(
hr.getEntity().getContent())
);
String data=br.readLine();
JSONArray ja=new JSONArray(data);
this.getContentResolver().delete(
Uri.parse(”content://rmutp.students/stu”),
null,null);
for(int i=0;i<ja.length();i++)
{
JSONObject jo=ja.getJSONObject(i);
//Toast.makeText(this,
// jo.getString(”studentid”),
// Toast.LENGTH_LONG).show();
ContentValues values=new ContentValues();
values.put(”studentid”, jo.getString(”studentid”));
values.put(”firstname”, jo.getString(”firstname”));
values.put(”lastname”, jo.getString(”lastname”));
values.put(”level”, jo.getInt(”level”));
this.getContentResolver().insert(Uri.parse(”content://rmutp.students/stu”),
values);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.stopSelf();
}
}
——————————————

StudentView.xml

package com.example.mywebserivce;
import android.app.ListActivity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.widget.SimpleCursorAdapter;
public class StudentView extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Cursor output=this.getContentResolver().query(
Uri.parse(”content://rmutp.students/stu”),
null, null,null, null);
SimpleCursorAdapter sca=
new SimpleCursorAdapter(
this,
R.layout.listlayout,
output,
new String[]{”studentid”,
“firstname”,”lastname”},
new int[]{R.id.textView1,R.id.textView2,
R.id.textView3}
);
this.setListAdapter(sca);
}
}

————————————————

MainActivity.java
package com.example.mywebserivce;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
}
public void OnWebservice(View view)
{
Intent i=new Intent(this,StudentService.class);
this.startService(i);
}
public void OnView(View view)
{
Intent i=new Intent(this,StudentUpdateService.class);
this.startService(i);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}

——————————–

StudentUpdateService.java
package com.example.mywebserivce;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class StudentUpdateService extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
Timer timer=null;
NotificationManager nm=null;
@Override
public void onCreate() {
super.onCreate();
timer=new Timer();
timer.scheduleAtFixedRate(
new TimerTask(){
@SuppressWarnings(”deprecation”)
@Override
public void run() {
nm=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
@SuppressWarnings(”deprecation”)
Notification no=new Notification(
R.drawable.ic_launcher,
“Test Notification”,
System.currentTimeMillis());
PendingIntent pi=PendingIntent.getActivity(
StudentUpdateService.this,
0,new Intent(
StudentUpdateService.this,StudentView.class),0);
no.setLatestEventInfo(StudentUpdateService.this,
“New Data!!!”,”Data1″,pi);
nm.notify(R.string.app_name,no);
}},0,60000);
}
}

—————————————-
Result
391
After Drag picture down it will appear as below

38

After click New Data!! It will show as below. It get data from data that made by VS c# show

39

————————

Form1.cs (VS C# program)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel;
using System.ServiceModel.Web;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
StudentDBDataContext studentdb = new StudentDBDataContext();
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = studentdb.Students; //Show all
//dataGridView1.DataSource = studentdb.Students.Where(
//  g => g.studentid == “001″);
}
private void button2_Click(object sender, EventArgs e) //insert
{
Student newstudent = new Student();
newstudent.studentid = textBox1.Text;
newstudent.firstname = textBox2.Text;
newstudent.lastname = textBox3.Text;
newstudent.level = Int32.Parse(textBox4.Text);
studentdb.Students.InsertOnSubmit(newstudent);
studentdb.SubmitChanges();
}
Student std;
private void button3_Click(object sender, EventArgs e) //find
{
std = studentdb.Students.Where(
s => s.studentid==textBox1.Text).SingleOrDefault();
if (studentdb != null)
{
textBox2.Text = std.firstname;
textBox3.Text = std.lastname;
textBox4.Text = std.level.ToString();
}
}
private void button4_Click(object sender, EventArgs e) //Update
{
std.firstname = textBox2.Text;
std.lastname = textBox3.Text;
std.level = Int32.Parse(textBox4.Text);
studentdb.SubmitChanges();
}
private void button5_Click(object sender, EventArgs e) //Delete
{
studentdb.Students.DeleteOnSubmit(std);
studentdb.SubmitChanges();
}
private void Form1_Load(object sender, EventArgs e)
{
WebServiceHost ws = new WebServiceHost(
typeof(StudentSerive),
new Uri(”http://172.16.28.61:8888″));
ws.AddServiceEndpoint(typeof(iStudent),
new WebHttpBinding(),”students”);
//***
ws.Open();
}
[ServiceContract]
public interface iStudent
{
[OperationContract,
WebGet(ResponseFormat = WebMessageFormat.Json)]
List<Student> getAllStudents();
}
public class StudentSerive : iStudent
{
StudentDBDataContext studentdb = new StudentDBDataContext();
public List<Student> getAllStudents()
{
return studentdb.Students.ToList();
}
}
public List<Student> getAllStudents()
{
//System.Threading.Thread.Sleep(10000);
return studentdb.Students.ToList();
}
}
}

จากการฝึกอบรม Android วิทยากร อ.โชคชัย จันทร์เชย

 

Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *