am new in android studio and I am trying to make my simple app get JSON data from URL using Volley , everything good but i have problem with time format Timestamp in URL i want him show in local time .
my code
package imo.meteoiraq;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.security.Timestamp;
public class MainActivity extends AppCompatActivity {
RequestQueue rq;
TextView timeDesc,tempDesc,windspeedDesc,windguestDesc,humdityDesc;
int ages;
int temp;
int windspeed;
int windguest;
int humdity;
String timeupdate;
String url="/stationlookup?station=I1410&units=metric&v=2.0&format=json";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rq= Volley.newRequestQueue(this);
timeDesc= (TextView) findViewById(R.id.timeupdateDesc);
tempDesc= (TextView) findViewById(R.id.tempid);
windspeedDesc= (TextView) findViewById(R.id.windid);
windguestDesc= (TextView) findViewById(R.id.windgustid);
humdityDesc= (TextView) findViewById(R.id.humdid);
sendjsonrequest();
}
public void sendjsonrequest(){
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject stationsJO = response.getJSONObject("stations");
JSONObject I1410JO = stationsJO.getJSONObject("I1410");
temp = I1410JO.getInt("temperature");
windspeed = I1410JO.getInt("wind_speed");
windguest = I1410JO.getInt("wind_gust_speed");
humdity = I1410JO.getInt("humidity");
timeupdate = I1410JO.getString(Timestamp,"updated");
timeDesc.setText(timeupdate);
tempDesc.setText(Integer.toString(temp));
windspeedDesc.setText(Integer.toString(windspeed));
windguestDesc.setText(Integer.toString(windguest));
humdityDesc.setText(Integer.toString(humdity));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
rq.add(jsonObjectRequest);
}
}
json
{
"stations": {
"I1410": {
"updated": 1499842858,
"ageh": 0,
"agem": 1,
"ages": 6,
"type": "PWS",
"wind_dir_degrees": 270,
"wind_speed": 7.2,
"wind_gust_speed": 9.7,
"humidity": 12,
"temperature": 38.9,
"precip_rate": null,
"precip_today": 0,
"pressure": 1000.56,
"dewpoint": null,
"windchill": null
}
}
}
For converting a time stamp to Date format
Checkout Imports
//Imports are as below
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
//convert timestamp (seconds) to milliseconds
String timeupdate = "1499842858";
long timestamp = Long.parseLong(timeupdate) * 1000L;
Toast.makeText(getApplicationContext(),"Date:"+getDate(timestamp),Toast.LENGTH_SHORT).show();
timeDesc.setText(getDate(timestamp));
private String getDate(long timeStamp){
try{
DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
Date netDate = (new Date(timeStamp));
return sdf.format(netDate);
}
catch(Exception ex){
return "xx";
}
}
I checked code and its working fine
you can use this code :
long millisecond = I1410JO.getLong("updated")*1000L;
timeupdate = DateFormat.format("MM/dd/yyyy", new Date(millisecond)).toString();
timeDesc.setText(timeupdate);
Related
I am beginner in android development.
I used volley library for HTTP connections
The program is supposed to load data from the server into a list called listItems and push it to a recyclerview. The program works fine but I can't make access to list values outside the procedure loadRecyclerView
This is the code:
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerViewAdapter adapter;
private ArrayList<ListItem> listItems;
private TextView dateTextView;
private static final String URL_DATA = "http://10.0.2.2:8080/json/csv.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dateTextView = (TextView) findViewById(R.id.Date);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
dateTextView.setText("Date:" + simpleDateFormat.format(new Date()));
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
recyclerView.hasFixedSize();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems = new ArrayList<>();
loadRecyclerView();
// I want to access values of the list right here
Log.i("list", "onCreate: "+this.listItems.size());
}
private void loadRecyclerView() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Chargement...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(
Request.Method.GET,
URL_DATA,
// this is an anonymous class, make it a public class and instantiate from it
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
progressDialog.dismiss();
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String salle = object.getString("salle");
String matiere = object.getString("matiere");
String groupe = object.getString("groupe");
String nomEnseignant = object.getString("nomEnseignant");
String typeSeance = "";//object.getString("typeSeance");
String seance = ""; //object.getString("seance");
String regime = "";//object.getString("regime");
ListItem listItem = new ListItem(matiere,typeSeance, groupe, salle, nomEnseignant,regime,"",seance,simpleDateFormat.format(new Date()));
listItems.add(listItem);
}
adapter = new RecyclerViewAdapter(listItems, getApplicationContext());
recyclerView.setAdapter(adapter);
Log.i("list", "onResponse: "+listItems.size());
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
if (error instanceof NetworkError) {
Toast.makeText(getApplicationContext(),"Cannot connect to Internet...Please check your connection!",Toast.LENGTH_SHORT).show();
}
else if (error instanceof ServerError) {
Toast.makeText(getApplicationContext(),"The server could not be found. Please try again after some time!!",Toast.LENGTH_SHORT).show();
} else if (error instanceof AuthFailureError) {
Toast.makeText(getApplicationContext(),"AuthFailureError",Toast.LENGTH_SHORT).show();
} else if (error instanceof ParseError) {
Toast.makeText(getApplicationContext(),"Parsing error! Please try again after some time!!",Toast.LENGTH_SHORT).show();
} else if (error instanceof NoConnectionError) {
Toast.makeText(getApplicationContext(),"NoConnectionError",Toast.LENGTH_SHORT).show();
} else if (error instanceof TimeoutError) {
Toast.makeText(getApplicationContext(),"Connection TimeOut! Please check your internet connection.",Toast.LENGTH_SHORT).show();
}
}
}
);
Log.i("list", "size: "+listItems.size());
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
I read on google that anonymous class can change attributes but the change is not maintained outside it.
Any solution?
String request is executed in the background thread. It finishes after your attempt to check the list size, so the list is empty yet. You will have filled list in onResponse() callback.
I have written a code to access the below api and get the corresponding values of namaz timings, but the onResponse method is not getting invoked. I have given internet permissions in the android manifest file. I am new to Android, please help.
While Installing app is not asking for internet permissions though I mentioned it in manifest file.
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class NamazTiming extends AppCompatActivity {
private TextView fazarId, zoharid, asarid, magribid, ishaid, location;
private RequestQueue mQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.namaz_timing);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Namaz Timings");
fazarId = findViewById(R.id.fazarid);
zoharid = findViewById(R.id.zoharid);
asarid = findViewById(R.id.asarid);
magribid = findViewById(R.id.magribid);
ishaid = findViewById(R.id.ishaid);
location = findViewById(R.id.location);
Button locationbutton = findViewById(R.id.locationbutton);
mQueue = Volley.newRequestQueue(this);
locationbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
jsonParse();
}
});
}
private void jsonParse() {
//String loc = location.getText().toString().trim();
String url ="https://muslimsalat.com/uravakonda.json?key=ba8d0b5ba55c6db3cebbe3fefd6090f8";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(NamazTiming.this, "Entered onresponse", Toast.LENGTH_SHORT).show();
try {
Toast.makeText(NamazTiming.this, "Entered into TRY", Toast.LENGTH_SHORT).show();
String Fazar = response.getJSONArray("items").getJSONObject(0).get("fajr").toString();
String Zohr = response.getJSONArray("items").getJSONObject(0).get("dhuhr").toString();
String Asar = response.getJSONArray("items").getJSONObject(0).get("asr").toString();
String Magrib = response.getJSONArray("items").getJSONObject(0).get("maghrib").toString();
String Isha = response.getJSONArray("items").getJSONObject(0).get("isha").toString();
fazarId.setText(Fazar);
zoharid.setText(Zohr);
asarid.setText(Asar);
magribid.setText(Magrib);
ishaid.setText(Isha);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(NamazTiming.this, "Please enter the lccation name", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Toast.makeText(NamazTiming.this, "Please enter the lccation name", Toast.LENGTH_SHORT).show();
}
});
}
You need to add your request object to the Volley queue (in your case, mQueue) in order for the request to be executed.
Example:
mQueue.add(request);
Internet permission is normal permission so the android system will not ask internet permission.
You just call this line:
mQueue.add(request);
end of the request.
Add below line after errorListener method at end of your request
mQueue.add("your request type");
I am new to the android studio and I am trying to make my simple app get JSON data from URL i.e fetch JSON data from the server with Volley in Android Studio. When I debug on my device, it works fine but don't show any data and I am sure there is something wrong
my code:
package imo.meteoiraq;
import android.app.DownloadManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
RequestQueue rq;
TextView nameText,descriptionText,fbUrlText,youtubeUrlTxt;
int humidity;
int wind_speed;
int temperature;
String url="/stationlookupstation=I1410&units=metric&v=2.0&format=json";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rq= Volley.newRequestQueue(this);
nameText= (TextView) findViewById(R.id.tempText);
descriptionText = (TextView) findViewById(R.id.wind_speed);
fbUrlText = (TextView) findViewById(R.id.humidity);
sendjsonrequest();
}
public void sendjsonrequest(){
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
temperature = response.getInt("temperature");
wind_speed= response.getInt("wind_speed");
humidity= response.getInt("type");
nameText.setText(temperature);
descriptionText.setText(humidity);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
rq.add(jsonObjectRequest);
}
}
my data json:
{
"stations": {
"I1410": {
"updated": 1499668936,
"ageh": 0,
"agem": 0,
"ages": 58,
"type": "PWS",
"wind_dir_degrees": 315,
"wind_speed": 6.1,
"wind_gust_speed": 11.1,
"humidity": 10,
"temperature": 40.5,
"precip_rate": null,
"precip_today": 0,
"pressure": 1002.26,
"dewpoint": null,
"windchill": null
}
}
}
first get JsonObject stations and I1410 , then use ages = I1410JO.getInt("ages");
JSONObject stationsJO = response.getJSONObject("stations");
JSONObject I1410JO = stationsJO.getJSONObject("I1410");
int ages = I1410JO.getInt("ages");
There are 2 issues in the program.
1st issue already explained by Rasoul Miri about accessing stationsJO JSON object and then I1410JO JSON object.
2nd issue is that temperature is not of integer format but of double format and so you need to use I1410JO.getDouble("temperature") to get it.
There is error in your Url and you have not parsed response correctly.Send Correct Url with proper(GET or POST) method.
I am getting x and y values from a JSON and creating graph using GraphView. How to implement X-axis as Dates.I am sharing my code, please see what is the mistake?
Here's my code :
import android.graphics.Color;
import android.icu.text.SimpleDateFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.Viewport;
import com.jjoe64.graphview.helper.DateAsXAxisLabelFormatter;
import com.jjoe64.graphview.helper.StaticLabelsFormatter;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.DataPointInterface;
import com.jjoe64.graphview.series.LineGraphSeries;
import com.jjoe64.graphview.series.OnDataPointTapListener;
import com.jjoe64.graphview.series.Series;
import java.security.Timestamp;
import java.sql.Time;
import java.text.ParseException;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.HashMap;
import java.util.ArrayList;
import java.lang.Double;
import java.util.Map;
import java.util.Random;
import garima.asynctask.library.HttpHandler;
import static com.example.garima.bitcoingraph.sortedHashMap.sortByValues;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
//URL to get JSON Array
private static String url = "https://api.blockchain.info/charts/market-price?format=json";
HashMap<String, String> valueslist;
//JSON Node Names
private static final String TAG_STATUS = "status";
private static final String TAG_NAME = "name";
private static final String TAG_UNIT = "unit";
private static final String TAG_PERIOD = "period";
private static final String TAG_DESCRIPTION = "description";
private LineGraphSeries<DataPoint> series;
//On the click of this Get Data Button we receive information from json
Button Btngetdata;
JSONArray user = null;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GraphView graph = (GraphView) findViewById(R.id.graph);
series = new LineGraphSeries<DataPoint>();
graph.addSeries(series);
series.setThickness(8);
series.setDrawDataPoints(true);
series.setOnDataPointTapListener(new OnDataPointTapListener() {
#Override
public void onTap(Series series, DataPointInterface dataPoint) {
Toast.makeText(MainActivity.this,"On Data Point clicked:"+dataPoint, Toast.LENGTH_SHORT).show();
}
});
//StaticLabelsFormatter staticLabelsFormatter = new StaticLabelsFormatter(graph);
//staticLabelsFormatter.setHorizontalLabels(new String[] { "Feb'16", "Mar'16","April'16","May'16","June'16","July'16","Aug'16","Sep'16","Oct'16","Nov'16","Dec'16","Jan'17"});
//graph.getGridLabelRenderer().setLabelFormatter(staticLabelsFormatter);
graph.getGridLabelRenderer().setLabelFormatter(new DateAsXAxisLabelFormatter(MainActivity.this));
//graph.getGridLabelRenderer().setNumHorizontalLabels(30); // only 4 because of the space
graph.getGridLabelRenderer().setHumanRounding(false);
Viewport viewport = graph.getViewport();
viewport.setYAxisBoundsManual(true);
viewport.setMinY(0);
viewport.setMaxY(1200);
viewport.setScalable(true);
viewport.setScrollable(true);
viewport.setScalableY(true);
viewport.setScrollableY(true);
//viewport.setXAxisBoundsManual(true);
valueslist = new HashMap<>();
Btngetdata = (Button) findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#RequiresApi(api = Build.VERSION_CODES.N)
private void addEntry(String Xax, String Yax) {
//int Xaxis_val = Integer.parseInt(Xax);
//Log.i(TAG, "addEntry: value of Xaxis val is" + Xaxis_val);
float Yaxis_val = Float.parseFloat(Yax);
Log.i(TAG, "addEntry: value of Y axis is " + Yaxis_val);
Date date= new Date();
SimpleDateFormat fmtOut = new SimpleDateFormat("dd/MM/yyyy");
try {
date=fmtOut.parse(Xax);
} catch (ParseException e) {
e.printStackTrace();
}
Log.i(TAG, "addEntry: date as x is"+date);
series.appendData(new DataPoint(date, Yaxis_val), true, 200);
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Main Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
private class JSONParse extends AsyncTask<Void, Void, Void> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String Status_Value = jsonObj.getString(TAG_STATUS);
String Name_Value = jsonObj.getString(TAG_NAME);
String Unit_Value = jsonObj.getString(TAG_UNIT);
String Period_Value = jsonObj.getString(TAG_PERIOD);
String Description_Value = jsonObj.getString(TAG_DESCRIPTION);
// Getting JSON Array node
JSONArray values = jsonObj.getJSONArray("values");
// looping through All Values
for (int i = 0; i < values.length(); i++) {
JSONObject c = values.getJSONObject(i);
String x_val = c.getString("x");
String y_val = c.getString("y");
// tmp hash map for single value
HashMap<String, String> val = new HashMap<>();
// adding each child node to HashMap key => value
val.put("x", x_val);
val.put("y", y_val);
// adding values to values list
valueslist.put(x_val, y_val);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
protected void onPostExecute(Void Result) {
pDialog.dismiss();
/* ListAdapter adapter = new SimpleAdapter(
MainActivity.this, valueslist,
R.layout.list_item, new String[]{"x", "y",
}, new int[]{R.id.x_var,
R.id.y_var});
lv.setAdapter(adapter); */
Log.i(TAG, "onPostExecute: value of list is" + valueslist);
ArrayList<String> xVals = new ArrayList<>();
/*ArrayList<Entry> yVals = new ArrayList<Entry>();
/*for(Map<String,String> map:valueslist){
String tagName = map.get(TAG_VALUEx);
Log.i(TAG, "onPostExecute: value is"+ tagName);
String tagNameY=map.get(TAG_VALUEy);
Log.i(TAG, "onPostExecute: value of y is"+tagNameY);
addEntry(tagName,tagNameY);
}*/
HashMap<String,String> sortedList=sortByValues(valueslist);
Log.i(TAG,"sorted hash map is "+sortedList);
for (Map.Entry<String, String> entry : sortedList.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
String tagName = entry.getKey();
long timestampString = Long.parseLong(tagName);
String value = new java.text.SimpleDateFormat("dd/MM/yyyy").
format(new java.util.Date(timestampString * 1000));
/*// String newval=value.substring(0, value.indexOf(' '));
Date date= new Date();
SimpleDateFormat fmtOut = new SimpleDateFormat("dd/MM/yyyy");
try {
date=fmtOut.parse(value);
} catch (ParseException e) {
e.printStackTrace();
}*/
String tagNameY=entry.getValue();
//Log.i(TAG, "onPostExecute: value of date is"+date);
addEntry(value,tagNameY);
}
}
}
}
Here's the error:
I/MainActivity: addEntry: date as x isTue Jan 03 00:00:00 GMT+01:00 2017
I/System.out: 1483488000 1126.7633375
I/MainActivity: addEntry: value of Y axis is 1126.7633
I/MainActivity: addEntry: date as x isWed Jan 04 00:00:00 GMT+01:00 2017
I/System.out: 1454457600 368.38
I/MainActivity: addEntry: value of Y axis is 368.38
I/MainActivity: addEntry: date as x isWed Feb 03 00:00:00 GMT+01:00 2016
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.garima.bitcoingraph, PID: 3095
java.lang.IllegalArgumentException: new x-value must be greater then the last value. x-values has to be ordered in ASC.
at com.jjoe64.graphview.series.BaseSeries.checkValueOrder(BaseSeries.java:486)
at com.jjoe64.graphview.series.BaseSeries.appendData(BaseSeries.java:408)
at com.jjoe64.graphview.series.LineGraphSeries.appendData(LineGraphSeries.java:646)
at com.jjoe64.graphview.series.BaseSeries.appendData(BaseSeries.java:464)
at com.example.garima.bitcoingraph.MainActivity.addEntry(MainActivity.java:177)
at com.example.garima.bitcoingraph.MainActivity.-wrap0(MainActivity.java)
at com.example.garima.bitcoingraph.MainActivity$JSONParse.onPostExecute(MainActivity.java:361)
at com.example.garima.bitcoingraph.MainActivity$JSONParse.onPostExecute(MainActivity.java:312)
at android.os.AsyncTask.finish(AsyncTask.java:660)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:677)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Application terminated.
java.lang.IllegalArgumentException: new x-value must be greater then
the last value. x-values has to be ordered in ASC.
I think you must order date in ascendant mode, then add to series of DataPoint.
Sorry if my english is not good.
I am using android studio ,mysql database and notepad++ for php files.
The database has a table named login and has 3 attributes:
id
firstname
lastname
all are of the type varchar.
When I try to execute this code of android and php I don't get any error and the code is executed successfully but the data from the database does not get displayed on the emulator.
*******************Android code************************
package com.example.digi.college;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
EditText firstname, lastname, id;
Button insert, show;
TextView result;
RequestQueue requestQueue;
String inserturl = "http://192.168.1.104/android/register.php";
String displayurl = "http://192.168.1.104/android/display.php";
String hello="hello how are you";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
id = (EditText) findViewById(R.id.editText);
firstname = (EditText) findViewById(R.id.editText2);
lastname = (EditText) findViewById(R.id.editText3);
insert = (Button) findViewById(R.id.button);
show = (Button) findViewById(R.id.button2);
result = (TextView) findViewById(R.id.textView);
requestQueue = Volley.newRequestQueue(getApplicationContext());
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
displayurl, new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
try {
JSONArray students = response.getJSONArray("students");
for (int i = 0; i < students.length(); i++) {
JSONObject login = students.getJSONObject(i);
String id = login.getString("id");
String firstname = login.getString("firstname");
String lastname = login.getString("lastname");
result.append(id+" "+firstname+" "+lastname+"\n");
}
result.append("===\n");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
}
});
insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringRequest request = new StringRequest(Request.Method.POST, inserturl, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> parameters = new HashMap<String, String>();
parameters.put("id",id.getText().toString());
parameters.put("firstname",firstname.getText().toString());
parameters.put("lastname",lastname.getText().toString());
return parameters;
}
};
requestQueue.add(request);
}
});
}
}
*****************Php Code for insert.php******************
<?php
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$id=$_POST['id'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$db = mysql_connect("localhost", "root", "");
mysql_select_db("ntu", $db);
$sql = mysql_query("INSERT INTO login (id,firstname,lastname) VALUES ('$id','$firstname', '$lastname')");
mysql_close($db);
}
?>
*************Php code for display.php*************
<?php
$db = mysql_connect("localhost", "root", "");
mysql_select_db("ntu", $db);
$sql = mysql_query("SELECT * FROM login");
$a = array();
$index = 0;
while($row = mysql_fetch_assoc($sql))
{
$a[$index] = $row;
$index++;
}
echo json_encode(array("students"=>$a));
mysql_close($db);
?>
I think you have missed the put the internet permission in androidmanifeast.xml file give internet permission and check.