Android HttpPost request to server - android

i want to send data from android SqLite database to my Codeigniter web App controller which take the post data and save it to MySql database
so i made buttn to make this sync task in android app and its code:
public void syncAttendance(View v) {
try
{
/** Retrieving data from database **/
//use cursor to keep all data
//cursor can keep data of any data type
Cursor c=db.rawQuery("select * from mytable", null);
int memNum = 1;
//move cursor to first position
c.moveToFirst();
//fetch all data one by one
do
{
//we can use c.getString(0) here
//or we can get data using column index
String memID = c.getString(c.getColumnIndex("memID"));
String currTime = c.getString(c.getColumnIndex("currTime"));
String dayName = c.getString(c.getColumnIndex("dayName"));
////////////////////////////////////////
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://mywebsite.com/index.php/admin/attendance/scan_qr");
JSONObject json = new JSONObject();
/** try {**/
// JSON data:
json.put("memID", memID);
json.put("currTime", currTime);
json.put("dayName", dayName);
JSONArray postjson=new JSONArray();
postjson.put(json);
// Post the data:
httppost.setHeader("json",json.toString());
httppost.getParams().setParameter("jsonpost",postjson);
// Execute HTTP Post Request
System.out.print(json);
HttpResponse response = httpclient.execute(httppost);
// for JSON:
if(response != null)
{
InputStream is = response.getEntity().getContent();
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();
}
}
text = sb.toString();
}
//tv.setText(text);
/**
}catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
**/
//////////////////////////////////////////
/** show confirmation toast **/
Toast toast = Toast.makeText(this, memNum + memID + currTime + dayName, Toast.LENGTH_LONG);
toast.show();
memNum ++;
//move next position until end of the data
}while(c.moveToNext());
/** show confirmation toast **/
Toast toast = Toast.makeText(this, "Synchronization Completed", Toast.LENGTH_LONG);
toast.show();
}
catch(Exception e)
{
e.printStackTrace();
}
}
and the php codeigniter controller code is:
public function scan_qr()
{
$json = $_SERVER['HTTP_JSON'];
var_dump($json);
$data = json_decode($json);
var_dump($data);
$memID = $data->memID;
$currTime = $data->currTime;
$dayName = $data->dayName;
$ma7abawy_year = 3;
$data= array(
'member_id' => $memID,
//'points' => $points,
'presence_time' => $currTime,
//'event' => $eventname,
'event_date' => $dayName,
'ma7abawy_year' => $ma7abawy_year
);
$this->db->insert('attendance',$data);
}
i have no exception but nothing is happened
any ideas would be appreciated

I would suggest to use retrofit (see API docs) library to consume the service. Afterwards, see what you get back in the response and it will be a simple matter of saving the data to the sqlite3 db. See example for saving data.

Related

HttpUrlConnection does not work on mobile device but on emulator

all of a sudden my mobile device can't connect to the local server anymore. async tasks are not executed and i just can't figure out why. slowly i'm getting really desperate because in my opinion i didn't change anything to cause this.
as an example, this is a background task which is not working
public class Login extends AsyncTask<String, Void, String>{
private String loginUrl = "http://...";
private int loginSuccess = 0;
public String getToken(String fromJson) throws JSONException {
JSONObject json = new JSONObject(fromJson);
if(json.has("api_authtoken")) {
loginSuccess = 1;
String appToken = json.getString("api_authtoken");
return appToken;
}
else {
return json.toString();
}
}
public String doInBackground(String... arg0) {
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String authToken;
try {
// get logged in to get the api_authtoken
String email = (String) arg0[0];
String password = (String) arg0[1];
URL url = new URL(loginUrl);
// Create the request and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
//put values of edittexts into json-Object
JSONObject data = new JSONObject();
try {
data.put("email", email);
data.put("password", password);
} catch(JSONException e) {
Log.e("EXCEPTION", "unexpected JSON exception", e);
e.printStackTrace();
}
urlConnection.connect();
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(data.toString());
wr.flush();
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
//read server response
while((line = reader.readLine()) != null) {
sb.append(line);
}
//receive server "answer"
try {
return getToken(sb.toString());
}catch(JSONException e) {
Log.e("LOG", "unexpected JSON exception", e);
e.printStackTrace();
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("MainActivity", "Error closing stream", e);
}
}
}
//return sb.toString();
return null;
}
catch(IOException e) {
Log.e("LoginTask", "Error ", e);
// If the code didn't successfully get the data, there's no point in attempting
// to parse it.
//forecastJsonStr = null;
return null;
}
}
public void onPostExecute(String result) {
super.onPostExecute(result);
//Log.v("RESULT", result);
if(result == null) {
CharSequence text = "no internet connection";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(MainActivity.this, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
}
if(loginSuccess == 0) {
// if the request wasn't successful
// give user a message via toast
CharSequence text = "wrong password or user. please try again";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(MainActivity.this, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
}
else {
// save token in shared preferences
SharedPreferences tokenPref = getSharedPreferences(getString(R.string.preference_token), Context.MODE_PRIVATE);
SharedPreferences.Editor editorToken = tokenPref.edit();
editorToken.putString(getString(R.string.saved_auth_token), result);
editorToken.commit();
//save login status = 1 in shared preferences
SharedPreferences loginPref = getSharedPreferences(getString(R.string.preference_logged_in), Context.MODE_PRIVATE);
SharedPreferences.Editor editorLogin = loginPref.edit();
editorLogin.putString(getString(R.string.saved_login), "1");
editorLogin.commit();
Intent mapsIntent = new Intent(getApplicationContext(), MapsActivity.class);
startActivity(mapsIntent);
}
}
}
HttpClient is not supported any more in sdk 23. You have to use URLConnection or downgrade to sdk 22 (compile 'com.android.support:appcompat-v7:22.2.0')
If you need sdk 23, add this to your gradle:
android {
useLibrary 'org.apache.http.legacy'
}
HttpClient won't import in Android Studio
You should think about using a HTTP library, there is a bunch of them on internet, some are really easy to use, optimize and errorless.
For example, Volley (made by Google, I really like this one), okHttp or Picasso (for image).
You should take a look at this.
If you want to send (output), for example with POST or PUT requests you need to use this :-
urlConnection.setDoOutput(true);
In your code :-
public class Login extends AsyncTask<String, Void, String>{
private String loginUrl = "http://...";
private int loginSuccess = 0;
public String getToken(String fromJson) throws JSONException {
JSONObject json = new JSONObject(fromJson);
if(json.has("api_authtoken")) {
loginSuccess = 1;
String appToken = json.getString("api_authtoken");
return appToken;
}
else {
return json.toString();
}
}
public String doInBackground(String... arg0) {
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String authToken;
try {
// get logged in to get the api_authtoken
String email = (String) arg0[0];
String password = (String) arg0[1];
URL url = new URL(loginUrl);
// Create the request and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setDoOutput(true); // HERE
//put values of edittexts into json-Object
JSONObject data = new JSONObject();
try {
data.put("email", email);
data.put("password", password);
} catch(JSONException e) {
Log.e("EXCEPTION", "unexpected JSON exception", e);
e.printStackTrace();
}
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(data.toString());
wr.flush();
urlConnection.connect();
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
//read server response
while((line = reader.readLine()) != null) {
sb.append(line);
}
//receive server "answer"
try {
return getToken(sb.toString());
}catch(JSONException e) {
Log.e("LOG", "unexpected JSON exception", e);
e.printStackTrace();
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("MainActivity", "Error closing stream", e);
}
}
}
//return sb.toString();
return null;
}
catch(IOException e) {
Log.e("LoginTask", "Error ", e);
// If the code didn't successfully get the data, there's no point in attempting
// to parse it.
//forecastJsonStr = null;
return null;
}
}
public void onPostExecute(String result) {
super.onPostExecute(result);
//Log.v("RESULT", result);
if(result == null) {
CharSequence text = "no internet connection";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(MainActivity.this, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
}
if(loginSuccess == 0) {
// if the request wasn't successful
// give user a message via toast
CharSequence text = "wrong password or user. please try again";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(MainActivity.this, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
}
else {
// save token in shared preferences
SharedPreferences tokenPref = getSharedPreferences(getString(R.string.preference_token), Context.MODE_PRIVATE);
SharedPreferences.Editor editorToken = tokenPref.edit();
editorToken.putString(getString(R.string.saved_auth_token), result);
editorToken.commit();
//save login status = 1 in shared preferences
SharedPreferences loginPref = getSharedPreferences(getString(R.string.preference_logged_in), Context.MODE_PRIVATE);
SharedPreferences.Editor editorLogin = loginPref.edit();
editorLogin.putString(getString(R.string.saved_login), "1");
editorLogin.commit();
Intent mapsIntent = new Intent(getApplicationContext(), MapsActivity.class);
startActivity(mapsIntent);
}
}
}

how to create a gridview of images dynamically

i am working on an app in which i have to populate gridview of images dynamically. I am getting an array of image ids from server, i am decoding json array and getting the image ids. now i have stored all the images in my drawable folder, i want to show the images of the ids i am getting from the json, but i am stuck at this point i don't know how this. help
this is my main activity
public class MainActivity extends Activity {
GridView grid ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
grid = (GridView)findViewById(R.id.grid_view);
grid.setAdapter(new Adapter(this));
Button play = (Button)findViewById(R.id.play);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
playgame();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
protected void playgame() throws JSONException {
if(cardcount >=1 ){
BufferedReader reader=null;
data_to_send = "userId=" + userId ;
try
{
Log.e("inside try block", "get text");
// Defined URL where to send data
URL url = new URL("http://172.16.10.5/Ankur/andapp/request_Play.php");
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data_to_send);
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
Log.e("inside", "while loop");
}
play_response = sb.toString();
}
catch(Exception ex)
{
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
Log.e("play response from the server", ""+play_response);
}else
{
Toast.makeText(getApplicationContext(), "Sorry you don't have cards.buy a new card now", Toast.LENGTH_LONG).show();
}
JSONObject jo = new JSONObject(play_response);
pos1 = jo.getString("0");
pos2 = jo.getString("1");
pos3 = jo.getString("2");
pos4= jo.getString("3");
pos5 = jo.getString("4");
pos6= jo.getString("5");
pos7= jo.getString("6");
pos8= jo.getString("7");
pos9= jo.getString("8");
Log.e("value of 1st place of array", "array value "+pics[7]);
}
i recommend to use Loader. see this [documentation] (http://developer.android.com/guide/components/loaders.html)
thus you can transfer images loading in not ui thread in Loade

Cannot access Google Task API 403 Forbidden Response

I'm trying to connect to Google tasks without using Google client libraries. The following code returns a 403 forbidden error. Just not sure what I'm missing. Any guidance would be appreciated.
try {
Bundle options = new Bundle();
AccountManager manager = (AccountManager) getSystemService(ACCOUNT_SERVICE);
Account[] list = manager.getAccountsByType("com.google");
Account acct = list[0];
manager.invalidateAuthToken("com.google", null);
AccountManagerFuture<Bundle> acc = manager.getAuthToken(
acct,
"oauth2:https://www.googleapis.com/auth/tasks",
options, true, null, null);
Bundle bundle = acc.getResult();
String token = bundle
.getString(AccountManager.KEY_AUTHTOKEN);
Log.i("Token: ", token); // token does have value
String url = "https://www.googleapis.com/tasks/v1/users/#me/lists?key=long_winded_api_key_from_console_here";
HttpGet getRequest = new HttpGet(url);
getRequest.addHeader("client_id",
"clientID_from_console_here.apps.googleusercontent.com");
getRequest.addHeader("Authorization", "OAuth " + token);
HttpClient httpclient = new DefaultHttpClient();
String responseBody = httpclient.execute(getRequest,
new BasicResponseHandler()); // exception raised here
httpclient.execute(getRequest, new BasicResponseHandler());
Log.i("###", responseBody); // cannot get the response here
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // exception raised here
catch (OperationCanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AuthenticatorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
The following link shows how to get started using the Google Drive API from Android. It lets the user pick an account, gets consent from them then acquires a credentials object that can be used for API access with the Google client libraries:
https://developers.google.com/drive/quickstart-android
In your case you are trying to use the Tasks API, however the authentication parts should be identical:
In Step 2, enable the Tasks API instead.
Step 4 shows how to get an access token for a particular scope:
credential = GoogleAccountCredential.usingOAuth2(this, DriveScopes.DRIVE);
startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
Change the scope to the task API scope: https://www.googleapis.com/auth/tasks
Then I would recommend using the Google client libraries for the rest like the Drive example.
If for any reason you don't want to use the client libraries, and prefer crafting the HTTP request yourself, the authorization header you want should look like the following (unable to test right now):
getRequest.addHeader("Authorization", "Bearer " + credential.getToken());
I'm not perfectly sure if this is the cause, since you seem to do the same steps
I do, but you might want to try to use "Manage your tasks" instead of
"oauth2:https://www.googleapis.com/auth/tasks". That might be the reason for
the 403.
Here is how I connect without client libraries.
Full source available here:
apiTalker
First I get the access token:
public static final String AUTH_TOKEN_TYPE = "Manage your tasks";
public static String getAuthToken(AccountManager accountManager,
Account account, String authTokenType, boolean notifyAuthFailure) {
Log.d(TAG, "getAuthToken");
String authToken = "";
try {
// Might be invalid in the cache
authToken = accountManager.blockingGetAuthToken(account,
authTokenType, notifyAuthFailure);
accountManager.invalidateAuthToken("com.google", authToken);
authToken = accountManager.blockingGetAuthToken(account,
authTokenType, notifyAuthFailure);
}
catch (OperationCanceledException e) {
}
catch (AuthenticatorException e) {
}
catch (IOException e) {
}
return authToken;
}
Connecting and listing the available tasklists:
public static final String BASE_URL = "https://www.googleapis.com/tasks/v1/users/#me/lists";
public static String AuthUrlEnd() {
return "key=" + Config.GTASKS_API_KEY;
}
public static String AllLists(final String pageToken) {
String result = BASE_URL + "?";
if (pageToken != null && !pageToken.isEmpty()) {
result += "pageToken=" + pageToken + "&";
}
result += AuthUrlEnd();
return result;
}
public String getListOfLists(ArrayList<GoogleTaskList> list)
throws ClientProtocolException, IOException, JSONException {
String eTag = "";
String pageToken = null;
do {
HttpGet httpget = new HttpGet(AllLists(pageToken));
httpget.setHeader("Authorization", "OAuth " + authToken);
// Log.d(TAG, "request: " + AllLists());
AndroidHttpClient.modifyRequestToAcceptGzipResponse(httpget);
try {
JSONObject jsonResponse = (JSONObject) new JSONTokener(
parseResponse(client.execute(httpget))).nextValue();
// Log.d(TAG, jsonResponse.toString());
if (jsonResponse.isNull(NEXTPAGETOKEN)) {
pageToken = null;
}
else {
pageToken = jsonResponse.getString(NEXTPAGETOKEN);
}
// No lists
if (jsonResponse.isNull("items")) {
break;
}
eTag += jsonResponse.getString("etag");
JSONArray lists = jsonResponse.getJSONArray("items");
int size = lists.length();
int i;
// Lists will not carry etags, must fetch them individually if
// that
// is desired
for (i = 0; i < size; i++) {
JSONObject jsonList = lists.getJSONObject(i);
//Log.d("nononsenseapps", jsonList.toString(2));
list.add(new GoogleTaskList(jsonList, accountName));
}
}
catch (PreconditionException e) {
// // Can not happen in this case since we don't have any etag!
// } catch (NotModifiedException e) {
// // Can not happen in this case since we don't have any etag!
// }
}
} while (pageToken != null);
return eTag;
}
Here is how I parse the response:
public static String parseResponse(HttpResponse response)
throws ClientProtocolException, PreconditionException {
String page = "";
BufferedReader in = null;
Log.d(TAG, "HTTP Response Code: "
+ response.getStatusLine().getStatusCode());
if (response.getStatusLine().getStatusCode() == 403) {
// Invalid authtoken
throw new ClientProtocolException("Status: 403, Invalid authcode");
}
else if (response.getStatusLine().getStatusCode() == 412) { //
/*
* Precondition failed. Object has been modified on server, can't do
* update
*/
throw new PreconditionException(
"Etags don't match, can not perform update. Resolve the conflict then update without etag");
}
/*
* else if (response.getStatusLine().getStatusCode() == 304) { throw new
* NotModifiedException(); }
*/
else if (response.getStatusLine().getStatusCode() == 400) {
// Warning: can happen for a legitimate case
// This happens if you try to delete the default list.
// Resolv it by considering the delete successful. List will still
// exist on server, but all tasks will be deleted from it.
// A successful delete returns an empty response.
// Make a log entry about it anyway though
Log.d(TAG,
"Response was 400. Either we deleted the default list in app or did something really bad");
throw new PreconditionException(
"Tried to delete default list, undelete it");
}
else if (response.getStatusLine().getStatusCode() == 204) {
// Successful delete of a tasklist. return empty string as that is
// expected from delete
Log.d(TAG, "Response was 204: Successful delete");
return "";
}
else {
try {
if (response.getEntity() != null) {
// Only call getContent ONCE
InputStream content = AndroidHttpClient
.getUngzippedContent(response.getEntity());
if (content != null) {
in = new BufferedReader(new InputStreamReader(content));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
page = sb.toString();
//
// System.out.println(page);
}
}
}
catch (IOException e) {
}
finally {
if (in != null) {
try {
in.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
return page;
}

restarting AsyncTask in Service

I have Service and AsyncTask in it, which due to check updatings on the server. It have to be reexecuted if it get some data and also if it doesn't. So my AsyncTask implementation is :
private class DklabExecute extends AsyncTask<Void, String, Void> {
int count;
Calendar calendar = Calendar.getInstance();
java.util.Date now = calendar.getTime();
java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime());
String url = "http://192.168.0.250:81/?identifier=nspid_"+md5(LoginActivity.passUserId)+
",nspc&ncrnd="+Long.toString(currentTimestamp.getTime());
HttpGet rplPost = new HttpGet(url);
protected Void doInBackground(Void... args)
{
Log.i("service count", Integer.toString(count));
count ++;
Log.i("md5 func", md5(LoginActivity.passUserId));
String testData = "http://192.168.0.250/app_dev.php/api/comet/testOrder/";
JSONParser parser = new JSONParser();
DefaultHttpClient testClient = new DefaultHttpClient();
DefaultHttpClient rplClient = new DefaultHttpClient();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("", ""));
HttpGet httpTest = new HttpGet(testData);
httpTest.setHeader("Cookie", CookieStorage.getInstance().getArrayList().get(0).toString());
rplPost.setHeader("Cookie", CookieStorage.getInstance().getArrayList().get(0).toString());
try {
httpResponse = rplClient.execute(rplPost);
}
catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Header[] head = httpResponse.getAllHeaders();
Log.i("http Response",httpResponse.toString());
for (Header one:head)
{
Log.i("headers",one.toString());
}
Log.i("response code", Integer.toString(httpResponse.getStatusLine().getStatusCode()));
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line);// + "n");
}
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
json = sb.toString();
Log.i("rpl response",json);
if (new JSONArray(json) != null)
jArr = new JSONArray(json);
else
this.cancel(true);
JSONObject toObj = jArr.getJSONObject(0);
JSONObject data = toObj.getJSONObject(KEY_DATA);
if (data.has(KEY_ORDER))
{
for (Order a : ServiceMessages.orderExport)
{
Log.i("service before list", a.toString());
}
Log.i(" ", " ");
for (Order a : DashboardActivityAlt.forPrint)
{
Log.i("before dashboard list", a.toString());
}
JSONObject jsonOrder = data.getJSONObject(KEY_ORDER);
Gson gson = new Gson();
Order orderObj= gson.fromJson(jsonOrder.toString(), Order.class);
try
{
for (ListIterator<Order> itr = orderExport.listIterator(); itr.hasNext();)
{
Order a = itr.next();
Log.i("order count", a.toString());
if(orderObj.getOrderid()==a.getOrderid())
{
Log.i("Service","order was changed");
a = orderObj;
someMethod("Your order "+ orderObj.getTitle() + " was changed");
}
else
{
Log.i("Service","order"+ orderObj.getTitle()+" was added");
// DashboardActivityAlt.forPrint.add(0, orderObj);
ServiceMessages.orderExport.add(0,orderObj);
Log.i("status",Integer.toString(orderObj.getProcess_status().getProccessStatusId()));
someMethod("Your order "+ orderObj.getTitle() + " was added");
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
for (Order a : ServiceMessages.orderExport)
{
Log.i("service after list", a.toString());
}
Log.i(" ", " ");
for (Order a : DashboardActivityAlt.forPrint)
{
Log.i("after dashboard list", a.toString());
}
// intentOrder.putParcelableArrayListExtra("ordersService", orderExport);
sendBroadcast(intentOrder);
Log.i("after parse order",orderObj.toString());
Log.i("orders after updating",DashboardActivityAlt.orders.toString() );
}
else if (data.has(KEY_MESSAGE))
{
JSONObject jsonMessage = data.getJSONObject(KEY_MESSAGE);
Gson gson = new Gson();
Log.i("messages before parse", jsonMessage.toString());
for (Order a: DashboardActivityAlt.forPrint)
{
Log.i("messages count", Integer.toString(a.getCusThread().getMessages().size()));
}
Log.i("disparse message",jsonMessage.toString());
Message message = gson.fromJson(jsonMessage.toString(),Message.class);
Log.i("incomming message",message.toString());
JSONObject jsonThread = jsonMessage.getJSONObject(KEY_THREAD);
Threads thread = gson.fromJson(jsonThread.toString(),Threads.class);
Log.i("incomming thread",thread.toString());
Order orderChanged = new Order();
String orderName = null;
for(Order as : DashboardActivityAlt.forPrint)
{
if (as.getOrderid() == thread.getTreadOrder().getOrderid())
{
orderName = as.getTitle();
orderChanged = as;
Log.i("messages count after", Integer.toString(as.getCusThread().getMessages().size()));
}
}
Log.i("orderchanged",orderChanged.toString());
someMethod("Your order "+ thread.getTreadOrder().getTitle() + " was changed. Message was added");
orderChanged.getCusThread().addMessage(message);
sendBroadcast(intentMessage);
Log.i("messages service", "before sleep");
Log.i("messages service", "after sleep");
}
else
{
this.cancel(true);
}
}
catch (IllegalStateException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e2) {
rplClient.getConnectionManager().shutdown();
testClient.getConnectionManager().shutdown();
someMethod("You've lost internet connection. You should try later.");
e2.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void bitmap) {
this.cancel(true);
new DklabExecute().execute();
}
}
If I send some data to the server, it gives me back in JSON format via rpl server. Everything works good, but the problem is when I get some data from the server, AsyncTask reexecuted in onPostExecute() method and it is the same reapeted one or two times data in my list of orders. If I do not reexecute AsyncTask the listening happens only in onStartCommand() method but not permanently. Tell me please how can I implement this in the best manner...
if it's a service there's no reason to use an AsyncTask.
AyncTasks were build to deliver content back on the original thread (normally a UI thread), but services don't have those.
I suggest you use a ScheduledExecutorService instead http://developer.android.com/reference/java/util/concurrent/ScheduledExecutorService.html
private ScheduledExecutorService executor;
// call those on startCommand
executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleWithFixedDelay(run, 250,3000, TimeUnit.MILLISECONDS);
and have a Runnable doing the work
private Runnable run = new Runnable() {
#Override
public void run() {
// do your network stuff
}
};
and don't forget to cancel everything when your service stops
executor.shutdown();
edit:
or to use a thread in loop you can:
boolean isRunning;
.
// this on your start
Thread t = new Thread(run);
isRunning = true;
t.start();
the runnable
private Runnable run = new Runnable() {
#Override
public void run() {
while(isRunning){
// do your network stuff
}
}
};
and again, don't forget to finish it whenever the service finishes with:
isRunning = false;

how to create a string representation of json

hey there guys and girls i have this code that saves json as a string representation, i still haveing a little trouble understanding how the entity section works, and need to know how to change my code so that it works, this is the error im getting,
Error saving string java.lang.NumberFormatException: unable to parse '[{"story_name":"Story One"},{"story_name":"Story Two"},{"story_name":"Story Three"},{"story_name":"Story Four"},{"story_name":"Story Five"},{"story_name":"Story Six"}]' as integer
i was getting help from someone last night that almost got me there but still need a little more understanding of how it works and wht i get the parse error here is my full code
public class MainActivity extends Activity {
String entityString = null;
String storyObj = "";
Object json = null;
HttpEntity entity = null;
InputStream is = null;
Integer responseInteger = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//button that saves the file from mySQL
Button save = (Button) findViewById(R.id.downloadBtn);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveJson();
}
});
//Button that opens the file from InternalMemory
Button open = (Button) findViewById(R.id.showBtn);
open.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openJson();
}
});
//end of onCreate()
}
//saveJson pull a JSON file from mySQl server then saves that file in its JSON type eg .json
public void saveJson(){
TextView test = (TextView) findViewById(R.id.showView);
try{
//connects to mySQL
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://10.0.2.2/textures_story_list.php");
HttpResponse response = client.execute(post);
//captures the response
entity = response.getEntity();
InputStream entityStream = entity.getContent();
StringBuilder entityStringBuilder = new StringBuilder();
byte [] buffer = new byte[1024];
int bytesReadCount;
while ((bytesReadCount = entityStream.read(buffer)) > 0) {
entityStringBuilder.append(new String(buffer, 0, bytesReadCount));
}
entityString = entityStringBuilder.toString();
responseInteger = Integer.valueOf(entityString);
}catch(Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
try{
//is = entity.getContent();
String FILENAME = "story.json";
//gives file name
FileOutputStream output = openFileOutput(FILENAME, MODE_WORLD_READABLE);
//creates new StreamWriter
OutputStreamWriter writer = new OutputStreamWriter(output);
//writes json with file name story.json
writer.write(entityString);
writer.flush();
//closes writer
writer.close();
}catch(Exception e) {
Log.e("log_tag", "Error saving string "+e.toString());
}
//end of saveJson()
}
public void openJson(){
TextView test = (TextView) findViewById(R.id.showView);
try{
FileInputStream fileInput = openFileInput("story.json");
BufferedReader inputReader = new BufferedReader(new InputStreamReader(fileInput, "UTF-8"), 8);
StringBuilder strBuilder = new StringBuilder();
String line = null;
while ((line = inputReader.readLine()) != null) {
strBuilder.append(line + "\n");
}
fileInput.close();
storyObj = strBuilder.toString();
}catch(IOException e){
Log.e("log_tag", "Error building string "+e.toString());
}
try{
JSONArray jArray = new JSONArray(storyObj);
String storyNames = "";
for(int i = 0;i<jArray.length();i++){
storyNames += jArray.getJSONObject(i).getString("story_name") +"\n";
}
test.setText(storyNames);
}catch(JSONException e) {
Log.e("log_tag", "Error returning string "+e.toString());
}
return;
//and of openJson()
}
//end of class body
}
My guess it your code failed at this lines:
responseInteger = Integer.valueOf(entityString);
After a little inspection, I see that your JSON is:
[{"story_name":"Story One"},{"story_name":"Story Two"},{"story_name":"Story Three"},{"story_name":"Story Four"},{"story_name":"Story Five"},{"story_name":"Story Six"}]
A closer inspection using JSON Viewer, I see that your structure is like this:
The problem is
I don't see any integer in this JSON. You might have to use a combination of JSONObject and JSONArray to parse your it properly.
Your problem is this line
responseInteger = Integer.valueOf(entityString);
entityString is
'[{"story_name":"Story One"},{"story_name":"Story Two"},{"story_name":"Story Three"},{"story_name":"Story Four"},{"story_name":"Story Five"},{"story_name":"Story Six"}]'
And when Integer.valueOf tries to parse it, it can't parse it as an integer, so it throws a NumberFormatException.
Sample JSon string:
{
Stories:
[
{
"story_name": "Story One"
},
{
"story_name": "Story Two"
}
]
}
Create a Class:
public class Story
{
public String stort_name;
}
class CollectionOfStories
{
public List<Story> Stories;
public CollectionOfSections()
{
Stories= new ArrayList<Story>();
}
}
Finally:
private CollectionOfStories convertDataFromJSonToObject(String jsonString)
{
JSONObject jso;
CollectionOfStories colStories = new CollectionOfStories();
try
{
jso = new JSONObject(jsonString);
JSONArray ja = jso.getJSONArray("Stories");
for (int i = 0; i < ja.length(); i++)
{
Story s = new Story();
JSONObject jsonSection = ja.getJSONObject(i);
s.stort_name = jsonSection.getString("story_name");
//add it to sections list
colStories.Stories.add(s);
}
}
catch (NumberFormatException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return colStories;
}

Categories

Resources