I have a ProgressDialog that retrieves in background data from database by executing php script.
I'm using gson Google library. php script is working well when executed from browser:
{"surveys":[{"id_survey":"1","question_survey":"Are you happy with the actual government?","answer_yes":"50","answer_no":"20"}],"success":1}
However, ProgressDialog background treatment is not working well:
#Override
protected Void doInBackground(Void... params) {
String url = "http://192.168.1.4/tn_surveys/get_all_surveys.php";
HttpGet getRequest = new HttpGet(url);
Log.d("GETREQUEST",getRequest.toString());
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
Log.d("URL1",url);
HttpResponse getResponse = httpClient.execute(getRequest);
Log.d("GETRESPONSE",getResponse.toString());
final int statusCode = getResponse.getStatusLine().getStatusCode();
Log.d("STATUSCODE",Integer.toString(statusCode));
Log.d("HTTPSTATUSOK",Integer.toString(HttpStatus.SC_OK));
if (statusCode != HttpStatus.SC_OK) {
Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
Log.d("RESPONSEENTITY",getResponseEntity.toString());
InputStream httpResponseStream = getResponseEntity.getContent();
Log.d("HTTPRESPONSESTREAM",httpResponseStream.toString());
Reader inputStreamReader = new InputStreamReader(httpResponseStream);
Gson gson = new Gson();
this.response = gson.fromJson(inputStreamReader, Response.class);
}
catch (IOException e) {
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Log.d("HELLO","HELLO");
StringBuilder builder = new StringBuilder();
Log.d("STRINGBUILDER","STRINGBUILDER");
for (Survey survey : this.response.data) {
String x= survey.getQuestion_survey();
Log.d("QUESTION",x);
builder.append(String.format("<br>ID Survey: <b>%s</b><br> <br>Question: <b>%s</b><br> <br>Answer YES: <b>%s</b><br> <br>Answer NO: <b>%s</b><br><br><br>", survey.getId_survey(), survey.getQuestion_survey(),survey.getAnswer_yes(),survey.getAnswer_no()));
}
Log.d("OUT FOR","OUT");
capitalTextView.setText(Html.fromHtml(builder.toString()));
progressDialog.cancel();
}
HELLO Log is displayed.
STRINGBUILDER Log is displayed.
QUESTION Log is NOT displayed.
OUT FOR Log is displayed.
Survey Class:
public class Survey {
int id_survey;
String question_survey;
int answer_yes;
int answer_no;
public Survey() {
this.id_survey = 0;
this.question_survey = "";
this.answer_yes=0;
this.answer_no=0;
}
public int getId_survey() {
return id_survey;
}
public String getQuestion_survey() {
return question_survey;
}
public int getAnswer_yes() {
return answer_yes;
}
public int getAnswer_no() {
return answer_no;
}
}
Response Class:
public class Response {
ArrayList<Survey> data;
public Response() {
data = new ArrayList<Survey>();
}
}
Any help please concerning WHY the FOR loop is not executed.
Thank you for helping.
Any help please concerning WHY the FOR loop is not executed.
Simply put: data is empty. (So there is nothing for the loop to iterate over...)
Try something like this, from GSON's documentation:
Type listType = new TypeToken<List<String>>() {}.getType();
List<String> target = new LinkedList<String>();
target.add("blah");
Gson gson = new Gson();
String json = gson.toJson(target, listType);
List<String> target2 = gson.fromJson(json, listType);
I haven't used GSON myself, but there are other examples of how to read lists:
Android gson deserialization into list
GSON : custom object deserialization
Your onPostExecute takes in a parameter called result. Your for loop iterates over the elements in an instance variable called response. Are they supposed to be the same?
Related
I have recently made an application in android studio 2.3 to show data from a server the link that I use is working properly in a browser and data is shown successfully in json format. But in my application I can't retrieve these data, I add avolley lib in my app gradle file like this :
compile 'com.mcxiaoke.volley:library:1.0.18'
The code I use in MainActivity is :
public class MainActivity extends AppCompatActivity {
RequestQueue rq;
String url = "http://abdulwahid.esy.es/show.php";
TextView txtshow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtshow = (TextView) findViewById(R.id.txtshow);
rq = Volley.newRequestQueue(this);
JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jarr = response.getJSONArray("allstudents");
for (int i = 0; i < jarr.length(); i++) {
JSONObject res = jarr.getJSONObject(i);
String id = res.getString("id");
String name = res.getString("name");
String info = res.getString("info");
txtshow.append("\n" + id + " - " + name + "\n" + info + "\n" + "------------------" + "\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
}
});
rq.add(jor);
}
The link of php file that I use is executed successfully in a web browser.
How to show data in my application or is there another code or library to use for retrieving data form online ?
you can use StringRequest instead of jsonObject with the new library of volley
compile 'com.android.volley:volley:1.0.0'
Use this code to retrieve data, in string line your data will be appended as a complete string as shown in browser
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://abdulwahid.esy.es/show.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
The problem is that the Content-Type header is not set in the response of your server. For Volley to be able to parse it, you will need that header set to application/json.
Add the following line in your show.php:
header('Content-Type: application/json');
Edit
After the above change, the response seems strange...
I can see strange characters in the response, that might be causing parsing issues on the client side.
I have an app that should send a the phone number and retrieve a value from the database, now I change the query and my code should retrieve values of multiple columns, So where changes should be in my code.
public class JSONTransmitter extends AsyncTask<JSONObject, Void, String>
{
HttpResponse response;
String url = "http://192.168.1.97:89/Derdeery/bankOsman.php";
private AsyncCallback asyncCallback;
public JSONTransmitter(Context context) {
// attach the callback to any context
asyncCallback = (AsyncCallback) context;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
asyncCallback.onResponse(result);
}
protected String doInBackground(JSONObject... data)
{
JSONObject json = data[0];
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
JSONObject jsonResponse = null;
HttpPost post = new HttpPost(url);
String resFromServer = "";
try {
StringEntity se = new StringEntity("json=" + json.toString());
post.addHeader("content-type", "application/x-www-form-urlencoded");
post.setEntity(se);
HttpResponse response;
response = client.execute(post);
resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());
Log.i("Response from server", resFromServer);
} catch (Exception e) {
e.printStackTrace();
}
return resFromServer;
}
public static interface AsyncCallback {
void onResponse(String res);
}
}
Here is something to consider:
First, in your php code (server-side), query your data perhaps separately. So for instance, you can get those that match column A and then query for those that match column B.
Generate Json for each (A and B accordingly)
Then create a single JSON object that contains the two sets of data like this:
{
"DataFromColumnA" : {},
"DataFromColumnB" : {}
}
Once you have made your HTTP request in your android code, you can get the specific data by getting "DataFromColumnA" json Object and B respectively.
I hope this helps you get your problem solved!
I am trying to parse huge json using gson library and my main idea is to get one value from each object and save it as String. This the json file i am using. And this is the code i am using to parse the json:
public class PostsActivity extends Activity {
private static final String TAG = "PostsActivity";
private List<Post> posts;
public TextView textss;
public int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_posts);
textss = (TextView)findViewById(R.id.texts);
PostFetcher fetcher = new PostFetcher();
fetcher.execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.posts, menu);
return true;
}
private void handlePostsList(List<Post> posts) {
this.posts = posts;
runOnUiThread(new Runnable() {
#Override
public void run() {
for(Post post : PostsActivity.this.posts) {
Toast.makeText(PostsActivity.this, post.title + " " + i, Toast.LENGTH_SHORT).show();
}
}
});
}
private void failedLoadingPosts() {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(PostsActivity.this, "Failed to load Posts. Have a look at LogCat. bls bls bls " , Toast.LENGTH_SHORT).show();
}
});
}
private class PostFetcher extends AsyncTask<Void, Void, String> {
private static final String TAG = "PostFetcher";
public static final String SERVER_URL = "http://kylewbanks.com/rest/posts";
#Override
protected String doInBackground(Void... params) {
try {
//Create an HTTP client
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(SERVER_URL);
//Perform the request and check the status code
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
try {
for ( i = 0; i < 4; i++) {
//Read the server response and attempt to parse it as JSON
Reader reader = new InputStreamReader(content);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
Gson gson = gsonBuilder.create();
List<Post> posts = Arrays.asList(gson.fromJson(reader, Post[].class));
content.close();
handlePostsList(posts);
}
} catch (Exception ex) {
Log.e(TAG, "Failed to parse JSON due to: " + ex);
failedLoadingPosts();
}
} else {
Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode());
failedLoadingPosts();
}
} catch(Exception ex) {
Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
failedLoadingPosts();
}
return null;
}
}
}
I am still learning and what i understand is that all values are saved in one big list and later these values are displayed as in Toast. What i am trying to do is save a value in String like i would to it with json like this:
JSONArray arr = new JSONArray(result);
JSONObject jObj = arr.getJSONObject(0);
String date = jObj.getString("NeededString");
How can i achieve this by using Gson library?
Here's what I've tried as you want.
//Read the server response and attempt to parse it as JSON
Reader reader = new InputStreamReader(content);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
Gson gson = gsonBuilder.create();
//List<Post> posts = Arrays.asList(gson.fromJson(reader, Post[].class));
JsonArray posts = new JsonParser().parse(reader).getAsJsonArray();
// Get first element at index 0
Post post1 = gson.fromJson(posts.get(0).getAsJsonObject(), Post.class);
Log.d(TAG, "post1 .. " + post1.getTitle());
content.close();
//handlePostsList(posts);
First of all, I create a Gson JsonArray. And assign it by creating a new JsonParser which parses the reader as a JsonArray.
And then you can extract the first element of the posts by getting the element at index 0, and deserializes with respective Object.
I've used set/get for Post object so I get the title as post1.getTitle().
The log says
post1 .. Disabling Google Analytics in Development Using Only
JavaScript
I am new to Android development. In my project I'm trying to get data from a site and show that data in a listview.
I am getting String data with httpGet and I'm parsing it with json and then put the data in adapter to show. However, it doesn't look smooth and it's working very slowly.
I should get 10 initial elements, and then when scrolling down get new 10 elements (but very smoothly).
videoList = new ArrayList<Videos>();
new JSONAsyncTask().execute(
"http://speechyard.com/api/content/?type=videolist&page=1&perPage=10");
ListView listview = (ListView)getView().findViewById(R.id.list);
VideoAdapter(Context context, int resource, ArrayList<Videos> objects)
adapter = new VideoAdapter(getActivity().getApplicationContext(), R.layout.content_row, videoList);
listview.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
} #Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
final int lastItem = firstVisibleItem + visibleItemCount;
if(lastItem +2> pageNumber*10) {
pageNumber+=1;
Log.d(TAG,pageNumber.toString());
new JSONAsyncTask().execute("http://speechyard.com/api/content/?type=videolist&page="+pageNumber+"&perPage=10");
}}});
}
//*******get data from http
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
//*****set progress dialog
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(getActivity());
dialog.setCancelable(false);
}
//*************HTTP Get save in String data
#Override
protected Boolean doInBackground(String... urls) {
try {//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
//**********Optimization String data for JSON parsing
String newdata="{\"video\":"+data+"}";
JSONObject jsono = new JSONObject(newdata);
JSONArray jarray = jsono.getJSONArray("video");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Videos video = new Videos();
video.setName(object.getString("name"));
video.setId(object.getString("id"));
video.setCategory(object.getString("category"));
video.setTime(object.getString("time"));
video.setSubtitles(object.getString("subtitles"));
video.setYoutube(object.getString("youtube"));
video.setImage(object.getString("image"));
videoList.add(video);
}
return true;
suggestion : Use HttpURLConnection !
1. create JSONParser.java
public class JSONParser extends Thread
{
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
URL myUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) myUrl.openConnection();
connection.setConnectTimeout(2000);
connection.setReadTimeout(2000);
connection.connect();
is = connection.getInputStream();
} catch (Exception e) {
is = null;
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
json = "";
}
try {
jObj = new JSONObject(json);
} catch (JSONException e)
{
jObj = null;
}
return jObj;
}
}
Use like this.
private class JSONParse extends AsyncTask
{
#Override
protected void onPreExecute()
{
}
#Override
protected JSONObject doInBackground(String... args)
{
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json)
{
//json.get......
}
I can see a lot of things you could be doing better.
The best way to load data onto a Fragment is using an ArrayAdapter (because you want to load a list) and a Loader.
Your App could get so much better if you use Google Volley as network provider and GSON or Jackson for JSON so you don't need to write this kind of code
Videos video = new Videos();
video.setName(object.getString("name"));
video.setId(object.getString("id"));
Fragments should be only used to display data, not to get it from network or have network code on the Fragment. To get data from the server you always need to be working with a Loader.
Basically you need to create a Loader class that extends from AsyncTaskLoader<ArrayList<Videos>> and your fragment needs to implement LoaderManager.LoaderCallbacks<ArrayList<Videos>> on the Loader public ArrayList<Videos> loadInBackground() you should be requesting the data from server and returning an ArrayList of Videos.
I've got a little problem with parsing json into my android app.
This is how my json file looks like:
{
"internalName": "jerry91",
"dataVersion": 0,
"name": "Domin91",
"profileIconId": 578,
"revisionId": 0,
}
As You can see this structure is a little bit weird. I dont know how to read that data in my app. As I noticed those are all Objects not arrays :/
You can always use good old json.org lib. In your Java code :
First read your json file content into String;
Then parse it into JSONObject:
JSONObject myJson = new JSONObject(myJsonString);
// use myJson as needed, for example
String name = myJson.optString("name");
int profileIconId = myJson.optInt("profileIconId");
// etc
UPDATE 2018
After 5 years there is a new "standard" for parsing json on android. It's called moshi and one can consider it GSON 2.0. It's very similar but with design bugs fixed that are the first obstacles when you start using it.
https://github.com/square/moshi
First add it as a mvn dependency like this:
<dependency>
<groupId>com.squareup.moshi</groupId>
<artifactId>moshi-kotlin</artifactId>
<version>1.6.0</version>
</dependency>
After adding it we can use like so (taken from the examples):
String json = ...;
Moshi moshi = new Moshi.Builder().build();
JsonAdapter<BlackjackHand> jsonAdapter = moshi.adapter(BlackjackHand.class);
BlackjackHand blackjackHand = jsonAdapter.fromJson(json);
System.out.println(blackjackHand);
More infos on their GitHub page :)
[old]
I would recommend using Gson.
Here are some links for tutorials:
how to convert java objecto from json format using GSON
Parse JSON file using GSON
Simple GSON example
Converting JSON data to Java object
An alternative to Gson you could use Jackson.
Jackson in 5 minutes
how to convert java object to and from json
This libraries basically parse your JSON to a Java class you specified.
to know if string is JSONArray or JSONObject
JSONArray String is like this
[{
"internalName": "blaaa",
"dataVersion": 0,
"name": "Domin91",
"profileIconId": 578,
"revisionId": 0,
},
{
"internalName": "blooo",
"dataVersion": 0,
"name": "Domin91",
"profileIconId": 578,
"revisionId": 0,
}]
and this String as a JSONOject
{
"internalName": "domin91",
"dataVersion": 0,
"name": "Domin91",
"profileIconId": 578,
"revisionId": 0,
}
but how to call elements from JSONArray and JSONObject ?
JSNOObject info called like this
first fill object with data
JSONObject object = new JSONObject(
"{
\"internalName\": \"domin91\",
\"dataVersion\": 0,
\"name\": \"Domin91\",
\"profileIconId\": 578,
\"revisionId\": 0,
}"
);
now lets call information from object
String myusername = object.getString("internalName");
int dataVersion = object.getInt("dataVersion");
If you want to call information from JSONArray you must know what is the object position number or you have to loop JSONArray to get the information for example
looping array
for ( int i = 0; i < jsonarray.length() ; i++)
{
//this object inside array you can do whatever you want
JSONObject object = jsonarray.getJSONObject(i);
}
if i know the object position inside JSONArray ill call it like this
//0 mean first object inside array
JSONObject object = jsonarray.getJSONObject(0);
This part do in onBackground in AsyncTask
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
try {
result = json.getString("internalName");
data=json.getString("dataVersion");
ect..
} catch (JSONException e) {
e.printStackTrace();
}
JsonParser
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
I suggest you to use a library like gson as #jmeier wrote on his answer. But if you want to handle json with android's defaults, you can use something like this:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String s = new String("{\"internalName\": \"domin91\",\"dataVersion\": 0,\"name\": \"Domin91\",\"profileIconId\": 578,\"revisionId\": 0,}");
try {
MyObject myObject = new MyObject(s);
Log.d("MY_LOG", myObject.toString());
} catch (JSONException e) {
Log.d("MY_LOG", "ERROR:" + e.getMessage());
}
}
private static class MyObject {
private String internalName;
private int dataVersion;
private String name;
private int profileIconId;
private int revisionId;
public MyObject(String jsonAsString) throws JSONException {
this(new JSONObject(jsonAsString));
}
public MyObject(JSONObject jsonObject) throws JSONException {
this.internalName = (String) jsonObject.get("internalName");
this.dataVersion = (Integer) jsonObject.get("dataVersion");
this.name = (String) jsonObject.get("name");
this.profileIconId = (Integer) jsonObject.get("profileIconId");
this.revisionId = (Integer) jsonObject.get("revisionId");
}
#Override
public String toString() {
return "internalName=" + internalName +
"dataVersion=" + dataVersion +
"name=" + name +
"profileIconId=" + profileIconId +
"revisionId=" + revisionId;
}
}
}
Please checkout ig-json parser or Logan Square for fast and light JSON library.
For comparison, this is the stats from Logan Square developer.
Here you can parse any file from assets folder
fetch file from assets folder
public void loadFromAssets(){
try {
InputStream is = getAssets().open("yourfile.json");
readJsonStream(is);
} catch (IOException e) {
e.printStackTrace();
}
}
Convert JSON to your class object
public void readJsonStream(InputStream in) throws IOException {
Gson gson = new Gson();
JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
reader.setLenient(true);
int size = in.available();
Log.i("size", size + "");
reader.beginObject();
long starttime=System.currentTimeMillis();
while (reader.hasNext()) {
try {
Yourclass message = gson.fromJson(reader, Yourclass.class);
}
catch (Exception e){
Toast.makeText(this, e.getCause().toString(), Toast.LENGTH_SHORT).show();
}
}
reader.endObject();
long endtime=System.currentTimeMillis();
long diff=endtime-starttime;
int seconds= (int) (diff/1000);
Log.i("elapsed",seconds+"");
reader.close();
}