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
Related
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
Here is my code.
The image space remaining empty. Not being loaded.
What is my mistake here?
what kind of code i need again.
give more definition pls.
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog progressDialog;
private ListView listView;
// JSON data url
private static String Jsonurl = "http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors";
ArrayList<HashMap<String, String>> contactJsonList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactJsonList = new ArrayList<>();
listView = (ListView) findViewById(R.id.listview);
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HTTPHandler httpHandler = new HTTPHandler();
// request to json data url and getting response
String jsonString = httpHandler.makeServiceCall(Jsonurl);
Log.e(TAG, "Response from url: " + jsonString);
if (jsonString != null) {
try {
JSONObject jsonObject = new JSONObject(jsonString);
// Getting JSON Array node
JSONArray contacts = jsonObject.getJSONArray("actors");
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String name = c.getString("name");
String country = c.getString("country");
String spouse = c.getString("spouse");
String dob = c.getString("dob");
String description = c.getString("description");
String children = c.getString("children");
String image = c.getString("image");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("name", name);
contact.put("country", country);
contact.put("spouse", spouse);
contact.put("dob", dob);
contact.put("description", description);
contact.put("children", children);
contact.put("image", image);
// adding contact to contact list
contactJsonList.add(contact);
}
} 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, "Could not get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"Could not get json from server.",Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (progressDialog.isShowing())
progressDialog.dismiss();
/** * Updating parsed JSON data into ListView * */
ListAdapter adapter = new SimpleAdapter(MainActivity.this, contactJsonList, R.layout.row,
new String[]{"name","country", "spouse", "dob", "description", "children", "image"},
new int[]{R.id.name, R.id.country, R.id.spouse, R.id.dob, R.id.description, R.id.children, R.id.imageview});
listView.setAdapter(adapter);
}
}
}
thanks for your help
If you want to load image from URL Use custom adapter and use picasso or Glide library to load image.
or
If you want to use simpleAdapter then check this link Image from URL in ListView using SimpleAdapter
you can user Glide library to load image from url look the below code it can help you in simple way
compile this library
compile 'com.github.bumptech.glide:glide:4.0.0-RC0'
than load image like this
Glide.with(HomeClass.this)
.load(userProfileUrl)
.centerCrop()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.dontAnimate()
.into(imageview);
Do you want to load list of images from url? then
check out the link below, there is detailed example working with list of images using json with volly library.
Example
I hope this will help you.
I'm trying to show a progress spinner when my doInBackground is processing.
From what I've been reading, here is what I am doing :
public class SearchMoviesAsync extends AsyncTask<String, String, JSONArray> {
ProgressDialog pd;
JSONParser jsonParser = new JSONParser();
String URL = "http://localhost:3000/movies/search";
#Override
protected void onPreExecute() {
pd=ProgressDialog.show(SearchActivity.this,"","Please Wait",false);
}
#Override
protected JSONArray doInBackground(String... args) {
try {
HashMap<String, String> params = new HashMap<>();
Log.d("IDFB", args[0]);
Log.d("Search", args[1]);
params.put("idfb", args[0]);
params.put("search", args[1]);
Log.d("request", "starting");
JSONArray json = jsonParser.makeHttpRequest2(
URL, "POST", params);
if (json != null) {
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONArray json) {
pd.dismiss();
}
}
This code is inside my SearchActivity.
The http request takes around 10 seconds to proceed and I want to add this spinner to avoid "MyApplication is taking too long to respond..."
Right now the spinner doesn't show up. If I delete pd.dismiss(); in onPostExecute, it will be displayed after my request respond and never gets off.
Thanks
I want to send 3 strings from doInBackground to onPostExecute.
I managed to fetch the data and I can see them in Logs. Now how to use the data stored in Strings once the doInBackground completed its execution.
Here is my code.
public class MainActivity extends AppCompatActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://example.com/test.php";
// JSON Node names
private static final String tag_info = "info";
private static final String tag_success = "Success";
private static final String tag_message = "message";
private static final String tag_output = "output";
// contacts JSONArray
JSONArray info = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Calling async task to get json
new fetchInfo().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class fetchInfo extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
info = jsonObj.getJSONArray(tag_info);
JSONObject c = info.getJSONObject(0);
// I want to use these 3 strings in onPostExecute
String success = c.getString(tag_success);
String message = c.getString(tag_message);
String output = c.getString(tag_output);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
TextView successView = (TextView) findViewById(R.id.success_field);
successView.setText(success + " " + message + " " + output); // I want to print them here
}
}
}
Use String Array
protected String[] doInBackground(String[]... passing) {
String[] result = new String[3];
result[0]= c.getString(tag_success);
result[1] = c.getString(tag_message);
result[2] = c.getString(tag_output);
return result; //return result
}
protected void onPostExecute(String result[]) {
String a = result[0];
}
Bean class
public class BeanClass{
String message,success,output;
public BeanClass(String message,String success,String output){
this.message = message;
this.success = success;
this.output = output;
}
public String getMessage(){ return message;}
public String getSuccess(){ return success;}
public String getOutput(){ return output;}
}
change your async task to
private class fetchInfo extends AsyncTask<Void, Void, BeanClass> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Bean doInBackground(Void... arg0) {
// Creating service handler class instance
Bean result=null;
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
info = jsonObj.getJSONArray(tag_info);
JSONObject c = info.getJSONObject(0);
// I want to use these 3 strings in onPostExecute
String success = c.getString(tag_success);
String message = c.getString(tag_message);
String output = c.getString(tag_output);
result = new Bean(sucess,message,output);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return result;
}
#Override
protected void onPostExecute(Bean result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
if(result!=null){
TextView successView = (TextView) findViewById(R.id.success_field);
successView.setText(result.getSuccess() + " " + result.getMessage() + " " + result.getOutput()); // I want to print them here
}
}
}
try the simply this....... do not need to pass
public class MainActivity extends AppCompatActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://example.com/test.php";
// JSON Node names
private static final String tag_info = "info";
private static final String tag_success = "Success";
private static final String tag_message = "message";
private static final String tag_output = "output";
// contacts JSONArray
JSONArray info = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Calling async task to get json
new fetchInfo().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class fetchInfo extends AsyncTask<Void, Void, Void> {
String success = "";
String message = "";
String output = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
info = jsonObj.getJSONArray(tag_info);
JSONObject c = info.getJSONObject(0);
// I want to use these 3 strings in onPostExecute
success = c.getString(tag_success);
message = c.getString(tag_message);
output = c.getString(tag_output);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
TextView successView = (TextView) findViewById(R.id.success_field);
successView.setText(success + " " + message + " " + output); // I want to print them here
Log.e("First Value", success);
Log.e("Second Value", message);
Log.e("Third Value", output);
}
}
}
public class fetchInfo extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(Void... params) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
info = jsonObj.getJSONArray(tag_info);
JSONObject c = info.getJSONObject(0);
// I want to use these 3 strings in onPostExecute
String success = c.getString(tag_success);
String message = c.getString(tag_message);
String output = c.getString(tag_output);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return output;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (pDialog.isShowing())
pDialog.dismiss();
TextView successView = (TextView) findViewById(R.id.success_field);
successView.setText(s); // I want to print them here
}
}
Do this while declaring
Public class Do Task extends AsyncTask<Void, Void, String>{
then in doInBackground method
protected String[] doInBackground(String[]... passing) {
return result; //change it to a string from null
}
then in onPostExecute result is your string that you want
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
Let me know if you still face an issue.Mark this up if it helps.
I want show server json responce in listview.i get all value in hashmap i am confused about how to set that data in custom listview.please help me and show me the code
class viewticket extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pdialog = new ProgressDialog(UserLogedIn.this);
pdialog.setMessage("Loading....");
pdialog.setIndeterminate(false);
pdialog.setCancelable(false);
pdialog.show();
}
#Override
protected Void doInBackground(Void... params) {
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("userid", u_id));
JSONObject jsonArray = jpar.makeHttpRequest(URLMyTicket, "POST", param);
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(URLMyTicket, ServiceHandler.POST, param);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
contacts = new JSONArray(jsonStr);
int a=contacts.length();
Log.v(TAG,""+a);
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_PROB);
String email = c.getString(TAG_DESC);
HashMap<String, String> contact = new HashMap<String, String>();
contact.put(TAG_ID, id);
contact.put(TAG_PROB, name);
contact.put(TAG_DESC, email);
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
//What code to write
}
}
what should i write in onpost method and custom list class
Ticket_list.java
public class Ticket_list extends ArrayAdapter< String> {
HashMap<String, String> objects;
public Ticket_list(Context context, int resource, HashMap<String,String> objects) {
super(???? //what );
}
//What
}
Please help me to write onpost method code and code of Ticket_list
I highly recommend you to use RecyclerView instead of ListView and use Retrofit to send request and get the response as json.Take a look at these documents For RecyclerView.