How to get data with this Json - android

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

Related

JSON to textView?

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();
}
}

cannot find symbol method getJSONArray(String) Volley

hi everyone i am working on a android project where i have to retrive the data form JSON. here is my link
I am trying to get the data using the below code
public class DisplayUser extends AppCompatActivity {
private TextView textViewResult;
private ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_user);
textViewResult = (TextView) findViewById(R.id.check_data_id); // in this text view i will display the text
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
String url = statics_demo.USER_URL+"7";// this is fixed url where i am getting the data
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(DisplayUser.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
JSONObject result;
private void showJSON(String response) {
try {
JSONArray obj = response.getJSONArray("responseMs");
for (int i = 0; i < obj.length(); i++) {
JSONObject jsonObject = obj.getJSONObject(i);
String name = jsonObject.getString("name");
System.out.println("luckyyyyyy"+name);
// String type = jsonObject.getString("type");
// retrieve the values like this so on..
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}
When i run the code i am getting a erorr saying
"Error:(60, 37) error: cannot find symbol method getJSONArray(String)"
String s = "[]"; JsonParser parser = new JsonParser(); JsonElement tradeElement = parser.parse(s); JsonArray trade = tradeElement.getAsJsonArray();
you need to convert string to jsonarray first

Get JSON response in listview and how to show it in listview?

I am a beginner in Android. I want to get a JSON response in a list and show it in a ListView . How to do this?
Here is my code for JSON post.
public class NewTest extends AppCompatActivity { TextView
txtJson;
Button btnOkay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_test);
txtJson= (TextView) findViewById(R.id.txtJson);
assert (findViewById(R.id.btnOkay)) != null;
(findViewById(R.id.btnOkay)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { new TaskPostWebService("written url here").execute(((TextView)
findViewById(R.id.txtJson)).getText().toString());
}
}); }
private class TaskPostWebService extends AsyncTask<String,Void,String> {
private String url;
private ProgressDialog progressDialog;
private JSONParser jsonParser;
public TaskPostWebService(String url ){
this.url = url;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(NewTest.this,"","");
}
#Override
protected String doInBackground(String... params) {
String fact = "";
try {
final MediaType JSON = MediaType.parse("application/json");
android.util.Log.e("charset", "charset - " + JSON.charset());
OkHttpClient client = new OkHttpClient();
//Create a JSONObject with the data to be sent to the server
final JSONObject dataToSend = new JSONObject()
.put("nonce", "G9Ivek")
.put("iUserId", "477");
android.util.Log.e("data - ", "data - " + dataToSend.toString());
//Create request object
Request request = new Request.Builder()
.url("written url here")
.post(RequestBody.create(JSON, dataToSend.toString().getBytes(Charset.forName("UTF-8"))))
.addHeader("Content-Type", "application/json")
.build();
android.util.Log.e("request - ", "request - " + request.toString());
android.util.Log.e("headers - ", "headers - " + request.headers().toString());
android.util.Log.e("body - ", "body - " + request.body().toString());
//Make the request
Response response = client.newCall(request).execute();
android.util.Log.e("response", " " + response.body().string()); //Convert the response to String
String responseData = response.body().string();
//Construct JSONObject of the response string
JSONObject dataReceived = new JSONObject(responseData);
//See the response from the server
Log.i("response data", dataReceived.toString());
}
catch (Exception e){
e.printStackTrace();
}
return fact;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
TextView text = (TextView) findViewById(R.id.txtJson);
text.setText(s);
progressDialog.dismiss();
}
}
So, how can I get a response in a list and show it in a ListView?
Welcome to stackOverflow,
as you are beginner so before going to complete solutions, you can think and follow following steps.
1.Network request:
For network request, we have lib volley(by Google) and retrofit(by Square). You can use this for network request and response.
2.JSON Parsing: You can used eigther GSON lib or using JSONObject/ jsonArray to parse json data. I'll recommend you to write your own parsing code for better understanding of JSON parsing.
3.ListView data binding: At this step, you should have parsed data in list(other data structure can be used to store data also). Create Adapter and bind listview with adapters.
I have not provided solutions for this, you should implement yourself and let me know for any doubts. Hope this should work.
ArrayList<JSONObject> arrayListJson;
ArrayList<String> arrayList;
ArrayAdapter<String> adapter;
ListView listView = (ListView) fragmentView.findViewById(R.id.listView);
adapter = new ArrayAdapter<> (getActivity(), android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(adapter);
now in a separate thread:
JSONObject jResponse = new JSONObject(responseStr);
JSONArray jArray= jResponse.getJSONArray("OUTER_KEY");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
arrayList.add(jsonObject.optString("INNER_KEY"));
arrayListJson.add(jsonObject);
}
adapter.notifyDataSetChanged();

use json object with inner objects to android application

This is my json code from url.this objects not have a general objects name but {H0...H20}each containing 5 childs that imgtitle and imgtext too include tow childs.
{
"h0":{
" id ": 1092,
" imgtitle ": {"fa":"cc","en":"dd"},
" imgtext ": {"fa_IR":"zz","en_GB":""},
" url": "www.example.com"
}
"h1":{
" id ":20221,
" imgtitle ":{"fa":"","en":"example"},
" imgtext ":{"fa_IR":"bb","en_GB":""},
" url ":"www.example.com"
}
.
.
"h20" {...
}
}
my problem is
This code does not work. how fix it? and
What can I do if it works for imgtitle and imgtext??
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
uid = (TextView)findViewById(R.id.uid);
myurl = (TextView)findViewById(R.id.url);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
JSONObject myobject = new JSONObject("h0");
int id = myobject.getInt("id");
String myurl= myobject.getString("url");
uid.setText(""+id);
myurl.setText(myurl);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
You are not calling the correct jsonObject, have a look at your code...myObject is new json..so of course it will he empty. You should use
json.getJsonObject(h4). I'm answering using mobile so sorry about typos and formatting

Exact procedure to add an image through json android

Hello so I have already an expirience with AsyncTask so I can manage to get some data with PHP scripts from an SQL Server and parsed them with JSON. Now what I would want is to know how can I use the AsyncTask in order to load images to some activities. Also is there anyway that I can call the AsyncTask before the app starts? because that would be really helpful too.
I don't have any adapters I am just using this for the AsyncTask:
// The definition of our task class
private class PostTask extends AsyncTask<String, Integer, String> {
private String postName;
private JSONObject jsonvar = new JSONObject();
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
this.postName = params[0];
String status = "";
List<NameValuePair> values = new ArrayList<NameValuePair>();
values.add( new BasicNameValuePair( "username", this.postName ) );
final AndroidHttpClient client = AndroidHttpClient.newInstance( "" );
HttpResponse response = HttpHelper.postResponse( client, Register.phpUrl, values );
String data = HttpHelper.getData( response );
try {
jsonvar = new JSONObject(data);
status=jsonvar.getString("status");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
client.close();
return status;
}
// #Override
// protected void onProgressUpdate(Integer... values) {
// super.onProgressUpdate(values);
// }
#Override
protected void onPostExecute(String status) {
String session = "", status_message = " ";
try {
status_message = jsonvar.getString("status_message");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
super.onPostExecute(status);
}
}
}
As i can tell with information provided, supposing that what you read from your server is the image URL and obtain it in JSON format, what i would do is writing a listener to your AsyncTask, calling it in onPostExecute method, and loading it in your Activity using PicassoImagesLoader
Something like:
private class PostTask extends AsyncTask<String, Integer, String> {
public interface onLoadFinishedListener {
public void onLoadFinished(JSONObject response)
}
protected JSONObject onPostExecute(JSONObject response){
onLoadFinished(response);
}
}
And in your Activity:
public myActivity extends Activity implements PostTask.onLoadFinishedListener {
#Override
onLoadFinished(JSONObject response){
Picasso.with(this).load(response.getString("url")).into(imageView);
}
}
Something like this would help :)

Categories

Resources