learning_intern
Newbie
hi
I am trying to run a service that does my REST operations. i would like it to start as soon as my app starts and grab the records from the backend server and display them as a ListView inside a Tab Layout.
I found a post that asks more or less the same question of invoking an activity from a service, but there were no good replies, rather no one replied to it except the guy who asked the question, so i had to re-post it!
Right now i have an activity which basically has 3 buttons. first one is to create and start my service, second one is to stop it and the 3rd one is to display the records i get from my backend server through my service in a ListView inside a Tab Layout.
the part that i have been able to achieve is -
1. i was able to create the buttons and write their onclick listeners, so that they do the appropriate job that they are supposed to do
2. i was able to write a service that does a simple get and post and gets me the records from the backend server as a JSON document. i know it works because in my php script (that is resting on the server side) that returns me the JSON document, i also made a provision to write that Document in a text file so that i know that my GET/POST are working.
THE ISSUE that i am facing is that i am not able to find a way through which i could display my JSON document as a ListView inside a Tab layout .
And also where in my app should i be inserting those retrieved records in my SQLite3 database (in the service or in a separate activity) ( i have a DbAdapter file to help me with).
i would also provide my code -
and for my service class -
ProjectsActivity is an activity class where i would like to display the JSON document that i receive.
Thanks in advance!
I am trying to run a service that does my REST operations. i would like it to start as soon as my app starts and grab the records from the backend server and display them as a ListView inside a Tab Layout.
I found a post that asks more or less the same question of invoking an activity from a service, but there were no good replies, rather no one replied to it except the guy who asked the question, so i had to re-post it!
Right now i have an activity which basically has 3 buttons. first one is to create and start my service, second one is to stop it and the 3rd one is to display the records i get from my backend server through my service in a ListView inside a Tab Layout.
the part that i have been able to achieve is -
1. i was able to create the buttons and write their onclick listeners, so that they do the appropriate job that they are supposed to do
2. i was able to write a service that does a simple get and post and gets me the records from the backend server as a JSON document. i know it works because in my php script (that is resting on the server side) that returns me the JSON document, i also made a provision to write that Document in a text file so that i know that my GET/POST are working.
THE ISSUE that i am facing is that i am not able to find a way through which i could display my JSON document as a ListView inside a Tab layout .
And also where in my app should i be inserting those retrieved records in my SQLite3 database (in the service or in a separate activity) ( i have a DbAdapter file to help me with).
i would also provide my code -
Code:
package com.example;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class ServicesDemo extends Activity implements OnClickListener {
private static final String TAG = "ServicesDemo";
Button buttonStart, buttonStop, buttonShow;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonStart = (Button) findViewById(R.id.buttonStart);
buttonStop = (Button) findViewById(R.id.buttonStop);
buttonShow = (Button) findViewById(R.id.buttonShow);
buttonStart.setOnClickListener(this);
buttonStop.setOnClickListener(this);
buttonShow.setOnClickListener(this);
}
public void onClick(View src) {
switch (src.getId()) {
case R.id.buttonStart:
Log.d(TAG, "onClick: starting service");
startService(new Intent(this, MyService2.class));
break;
case R.id.buttonStop:
Log.d(TAG, "onClick: stopping service");
stopService(new Intent(this, MyService2.class));
break;
case R.id.buttonShow:
Log.d(TAG, "onClick: showing records");
startActivity(new Intent(this, ProjectsActivity.class));
break;
}
}
}
and for my service class -
Code:
package com.example;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyService2 extends Service {
private static final String TAG = "MyService";
private ArrayList <NameValuePair> params;
private ArrayList <NameValuePair> headers;
private String url;
private int responseCode;
private String message;
private String response;
public enum RequestMethod
{
GET,
POST
}
public String getResponse() {
return response;
}
public String getErrorMessage() {
return message;
}
public int getResponseCode() {
return responseCode;
}
public void SetURL(String url)
{
this.url = url;
params = new ArrayList<NameValuePair>();
headers = new ArrayList<NameValuePair>();
}
public void AddParam(String name, String value)
{
params.add(new BasicNameValuePair(name, value));
}
public void AddHeader(String name, String value)
{
headers.add(new BasicNameValuePair(name, value));
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
/*----------------------------------------------------------------------------*/
@Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
SetURL("http://192.148.1.1/testhttpphp.php");
AddParam("task_id","20");
}
@Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
try {
Execute(RequestMethod.POST);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e(TAG, "error is = "+ e.toString());
}
}
/*----------------------------------------------------------------------------*/
public void Execute(RequestMethod post) throws Exception
{
switch(post) {
case GET:
{
//add parameters
String combinedParams = "";
if(!params.isEmpty()){
combinedParams += "?";
for(NameValuePair p : params)
{
String paramString = p.getName() + "=" + p.getValue();
if(combinedParams.length() > 1)
{
combinedParams += "&" + paramString;
}
else
{
combinedParams += paramString;
}
}
}
HttpGet request = new HttpGet(url + combinedParams);
//add headers
for(NameValuePair h : headers)
{
request.addHeader(h.getName(), h.getValue());
}
executeRequest(request, url);
break;
}
case POST:
{
HttpPost request = new HttpPost(url);
//add headers
/* for(NameValuePair h : headers)
{
request.addHeader(h.getName(), h.getValue());
}*/
if(!params.isEmpty()){
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
}
executeRequest(request, url);
break;
}
}
}
private void executeRequest(HttpUriRequest request, String url)
{
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
try {
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
response = convertStreamToString(instream);
// Closing the input stream will trigger connection release
instream.close();
}
} catch (ClientProtocolException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
} catch (IOException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
}
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
ProjectsActivity is an activity class where i would like to display the JSON document that i receive.
Thanks in advance!