I have my app get JSON data from a link, but I need to get status from the JSON.
Status > Code and Msg.
Here is what I have working:
Screenshot:
I need to have it output >
Code : success (or fail, whatever the json says)
Msg : Licence updated.. (Or whatever the JSON spits out)
Any help would be nice or pointing me in the direction, thanks.
Some of my code:
public class doit extends AsyncTask<Void,Void,Void>{
String words;
public doit() throws JSONException {
}
#Override
protected Void doInBackground(Void... voids) {
try {
WebView wv = (WebView) findViewById(R.id.webview);
EditText messages = (EditText) findViewById(R.id.messages);
Document doc = Jsoup.connect("https://api.deepbot.tv/web/apply/namerefresh.php?s=" + messages.getText().toString()).get();
words=doc.text();
}catch(Exception e){e.printStackTrace();}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
texx.setText(words);
}
1. First create a JSONObject with response string words.
JSONObject jsonObject = new JSONObject(words);
2. Get the JSONObject status from your response JSONObject words:
JSONObject jsonObjectStatus = jsonObject.getJSONObject("status");
3. Finally, parse code and msg string from status JSONObject as below:
String code = jsonObjectStatus.getString("code");
String msg = jsonObjectStatus.getString("msg");
Update onPostExecute() as below:
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
try {
JSONObject jsonObject = new JSONObject(words);
JSONObject jsonObjectStatus = jsonObject.getJSONObject("status");
String code = jsonObjectStatus.getString("code");
String msg = jsonObjectStatus.getString("msg");
texx.setText("Code: " + code + "\nMessage: " + msg);
} catch (JSONException e) {
e.printStackTrace();
}
}
Checkout awesome library Gson
You just need to create Object for response, And you will get it like
Response response = gson.fromJson("words", Response.class);
response contains all your needs.
OR
You can go with json parser tutorials.
Blockquote
JSONObject jObj = arr.getJSONObject(words);
String date = jObj.getString("msg");
Blockquote
Try the following, just replace your return:
public class doit extends AsyncTask<Void,Void,Void>{
String words;
public doit() throws JSONException {
}
#Override
protected Void doInBackground(Void... voids) {
try {
WebView wv = (WebView) findViewById(R.id.webview);
EditText messages = (EditText) findViewById(R.id.messages);
Document doc = Jsoup.connect("https://api.deepbot.tv/web/apply/namerefresh.php?s=" + messages.getText().toString()).get();
words=doc.text();
}catch(Exception e){e.printStackTrace();}
return words;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
try {
JSONObject jObj = new JSONObject(words);
String code = jObj.getString("code");
String name = jObj.getString("msg");
texx.setText(code +" "+name);
} catch (JSONException e) {
e.printStackTrace();
}
}
Related
how to resolve this json for Android Studio
and need each item is individually displayed in the textview
Thank you all....
url content only
{"s":true,"code":0,"errors":[],"c":"2.54","y":"5.8","i":"2.9","x":"0"}
My Someone Activity
public class aFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_a, null);
super.onCreate(savedInstanceState);
new TransTask()
.execute("MYURL");
return view;
}
class TransTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
StringBuilder sb = new StringBuilder();
try {
URL url = new URL(params[0]);
BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()));
String line = in.readLine();
while(line!=null){
Log.d("HTTP", line);
sb.append(line);
line = in.readLine();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d("JSON", s);
parseJSON(s);
}
private void parseJSON(String s) {
try{
JSONObject jsonObject = new JSONObject(s);
String name = jsonObject.getString("s");
String title = jsonObject.getString("code");
String tag = jsonObject.getString("errors");
String info = jsonObject.getString("c");
String info = jsonObject.getString("y");
String inf = jsonObject.getString("i");
String in = jsonObject.getString("x");
}
catch(JSONException e) {
e.printStackTrace();
}
}
why super.onPostExecute(s); cannot resolve method 'onPostExecute(java.lang.string)'
You could set the values for various widgets in the 'onPostExecute' method for your AsyncTask.
Initialize a JSONObject with the string returned. Then use the various methods like getBoolean, getString, getDouble, etc. for the values. You can even get nested json objects or arrays using getJSONObject and getJSONArray methods. Using JSONObject will require you to handle a JSONException in your code.
JSONObject jsonObject = new JSONObject(stringObject);
boolean s = jsonObject.getBoolean("s");
int code = jsonObject.getInt("code");
JSONArray errors = jsonObject.getJSONArray("errors");
//Similar to above
Alternately, you can also use a library like GSON to deserialize your json.
I have a little problem with make a toast when my table database is null based on parsing json. I mean, when data is no result or no data found then make a toast " Sorry no data found". Any help would be greatly appreciated.
here my code for show the data
private void showEmployee(){
JSONObject jsonObject = null;
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(konfigurasi.TAG_JSON_ARRAY);
for(int i = 0; i<result.length(); i++){
JSONObject jo = result.getJSONObject(i);
String id = jo.getString(konfigurasi.TAG_ID);
String nama = jo.getString(konfigurasi.TAG_NAMA);
String pyg = jo.getString(konfigurasi.TAG_PENYELENGGARA);
String tmpt = jo.getString(konfigurasi.TAG_TEMPAT);
String tgl = jo.getString(konfigurasi.TAG_TGL);
String jam = jo.getString(konfigurasi.TAG_JAM);
String email = jo.getString(konfigurasi.TAG_EMAIL);
HashMap<String,String> employees = new HashMap<>();
employees.put(konfigurasi.TAG_ID,id);
employees.put(konfigurasi.TAG_NAMA,nama);
employees.put(konfigurasi.TAG_PENYELENGGARA,pyg);
employees.put(konfigurasi.TAG_TEMPAT,tmpt);
employees.put(konfigurasi.TAG_TGL,tgl);
employees.put(konfigurasi.TAG_JAM,jam);
employees.put(konfigurasi.TAG_EMAIL,email);
list.add(employees);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new MySimpleArrayAdapter(this, list);
listView.setAdapter(adapter);
}
And this for postexcetude code :
private void getJSON(){
class GetJSON extends AsyncTask<Void,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(TampilSemuaPgw.this,"Mengambil Data","Mohon Tunggu...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(s == null || s.length() == 0){
Toast.makeText(getApplicationContext(), "No Data",Toast.LENGTH_LONG).show();
}
// Dismiss the progress dialog
if (loading.isShowing())
loading.dismiss();
JSON_STRING = s;
showEmployee();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(konfigurasi.URL_GET_ALL);
return s;
}
}
GetJSON gj = new GetJSON();
gj.execute();
}
Update Code by KeLiuyue :
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(konfigurasi.URL_GET_ALL);
return s;
}
#Override
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("result");
if(jsonArray.length() == 0){
Toast.makeText(getApplicationContext(), "No Data", Toast.LENGTH_LONG).show();
if (loading.isShowing()){
loading.dismiss();
}
return;
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("TAG",s);
// Dismiss the progress dialog
if (loading.isShowing())
loading.dismiss();
JSON_STRING = s;
showEmployee();
}
Try this in your code .
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(konfigurasi.URL_GET_ALL);
return s;
}
#Override
protected void onPostExecute(String s) {
// edited here
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("result");
if(jsonArray.length() == 0){
Toast.makeText(getApplicationContext(), "No Data", Toast.LENGTH_LONG).show();
if (loading.isShowing()){
loading.dismiss();
}
return;
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("TAG",s);
// Dismiss the progress dialog
if (loading.isShowing())
loading.dismiss();
JSON_STRING = s;
showEmployee();
}
1.Determine return value whether is empty in doInBackground method
2.Determine param value whether is empty in onPostExecute method
You need to Debug this issue why your toast is not showing:
You have correctly put show Toast code in onPostExecute
Now to debug , first put a Log to know the value of s , whether it is ever null or empty.
If yes and still toast is not showing, move the dialog dismiss dialog before Toast and check.
If Toast still does not show debug your showEmployee() method as what it does.
I want to show data of below JSON:
{"success":true,"message":"","result":{"Bid":3924.01000000,"Ask":3925.00000000,"Last":3924.00000000}}
I am new in android and from all tutorials, I somehow access this data but I want to show only "Last" data figure but my code shows whole "result" string.
String firstname;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.name);
new AsyncTaskParseJson().execute();
}
// you can make this class as another java file so it will be separated from your main activity.
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
String yourJsonStringUrl = "https://bittrex.com/api/v1.1/public/getticker?market=usdt-btc";
// contacts JSONArray
JSONArray dataJsonArr = null;
protected void onPreExecute() {}
protected String doInBackground(String... arg0) {
try {
// instantiate our json parser
JSONParser jParser = new JSONParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
firstname = json.getString("result");
Log.e(TAG, "Last: " + firstname);
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {
tv.setText(""+firstname);
}
}
You are not making a network call. You are just parsing your Url. You need to make network call. You can use volley for this. In your onCreate method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.name);
RequestQueue queue = Volley.newRequestQueue(this);
String url ="https://bittrex.com/api/v1.1/public/getticker?market=usdt-btc";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject json = new JSONObject(response);
try {
JSONObject result = json.getJSONObject("result");
Double last = result.getDouble("Last");
tv.setText(String.valueOf(last));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
you need to define internet permission in Manifest.xml
<uses-permission android:name="android.permission.INTERNET" />
You need to include volley library for this http request. Include this in build.gradle of your app
dependencies {
.
.
compile 'com.android.volley:volley:1.0.0'
.
.
}
I think you should be able to do this
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
return "" + json.get("result").getDouble("Last");
The string is returned from doInBackground to onPostExecute in the strFromDoInBg variable, but if you prefer:
firstname = "" + json.get("result").getDouble("Last");
would also work
I am running the commands like so:
new GetGameScoresFromFuhantikAPI()
And my method for this is ->
private class GetGameScoresFromFuhantikAPI extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
MethodContants.showLog(TAG, "Loading FUHNATIK API", true);
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = API_URL + jsonFile;
// String url = "http://www.nfl.com/liveupdate/game-center/" + list.get(i) + "/" + list.get(i) + "_gtd.json";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from FUHNATIK API: " + url);
if (jsonStr != null) {
try {
//JSONObject object = new JSONObject(json);
JSONObject object = new JSONObject(jsonStr);
currentWeek = object.getString("pypwk");
currentWeekDB = object.getString("mdb");
JSONArray array = (JSONArray) object.get("g");
scheduleModelList = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
//TODO IF WE DONT PLAY THURSDAY GAMES PUT LIST.ADD IN HERE
// if (!array.getJSONObject(i).getString("-d").equals("Thu")){
//
// }
scheduleModelList.add(new ScheduleModel(array.getJSONObject(i).getString("-v"),
array.getJSONObject(i).getString("-h"),
array.getJSONObject(i).getString("-t"),
array.getJSONObject(i).getString("-d"),
array.getJSONObject(i).getString("-eid").substring(0, 8),
array.getJSONObject(i).getString("-t") + array.getJSONObject(i).getString("-q"),
array.getJSONObject(i).getString("-vnn"),
array.getJSONObject(i).getString("-hnn"),
"...select a team...",
array.getJSONObject(i).getString("-eid"),
array.getJSONObject(i).getString("-vs"),
array.getJSONObject(i).getString("-hs"),
array.getJSONObject(i).getString("-w")));
}
} catch (final JSONException e) {
Log.e(TAG, "FUHNATIK API: Json parsing error: " + e.getMessage());
}
} else {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e(TAG, "FUHNATIK API: Couldn't get json from server.");
Toast.makeText(getContext(), "Getting from ESPN", Toast.LENGTH_SHORT).show();
//new GetGameScoresFromESPN().execute();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
final ListViewAdapterResults adapter = new ListViewAdapterResults(listView.getContext(), scheduleModelList);
listView.setAdapter(adapter);
MethodContants.showLog(TAG, "DONE WITH LOADING FUHNATIK API", false);
}
}
I can't seem to figure out why the code never get ran. I ran through the debugger but I really can't pinpoint where this is failing out. Any help on this would be appreciated.
Eventually if the json file is not at this URL, I will be getting the json from NFL. However, Without this working, the ESPN won't work either, and I really can not figure out where the error is on my end. I have to assume this will be a pretty easy fix.
Again, as said before, any help would be very appreciated!!
In the above line of code you call the Class but you forgot to execute your asynctask. So no Overriden methods are called. Try this:
new GetGameScoresFromFuhantikAPI().execute();
If you want to pass something as argument, give parameters separated by coma like this:
new GetGameScoresFromFuhantikAPI().execute(arg0, arg1);
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_LONG).show();
System.out.println("my result:"+result);
try {
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String fname = jsonObject.getString("First_Name");
String lname = jsonObject.getString("Last_Name");
String mail = jsonObject.getString("Email");
System.out.println("fname:"+fname+" lname:"+lname+" email:"+mail);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
In the above code,
posting data to server and get response. i want individual response of first name, email. can you please rectify my mistake.
You should parse as JSONObject, not as JsonArray as per your response from the server.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_LONG).show();
System.out.println("my result:"+result);
try {
JSONObject jsonObject = new JSONObject(result);
String fname = jsonObject.optString("First_Name");
String lname = jsonObject.optString("Last_Name");
String mail = jsonObject.optString("Email");
System.out.println("fname:"+fname+" lname:"+lname+" email:"+mail);
}
catch (Exception e) {
e.printStackTrace();
}
}