json parsing using uri for listview in android - json

ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://jsonplaceholder.typicode.com/posts";
//JSON Node Names
// private static final String TAG_OS = "Employee";
private static final String TAG_USER= "userId";
private static final String TAG_NAME = "id";
private static final String TAG_TITLE = "title";
private static final String TAG_BODY = "body";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
ver = (TextView)findViewById(R.id.user);
name = (TextView)findViewById(R.id.id);
api = (TextView)findViewById(R.id.titile);
body =(TextView)findViewById(R.id.body);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#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 {
// Getting JSON Array from URL
android = json.getJSONArray("");
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_USER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_TITLE);
String body =c.getString(TAG_BODY);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_USER, ver);
map.put(TAG_NAME, name);
map.put(TAG_TITLE, api);
map.put(TAG_BODY, body);
list.add(map);
List=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, list,
R.layout.list_v,
new String[] { TAG_USER,TAG_NAME, TAG_TITLE,TAG_BODY }, new int[] {
R.id.user,R.id.id, R.id.titile,R.id.body});
List.setAdapter(adapter);
List.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+list.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
json parse:-
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, "iso-8859-1"), 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;
}
}
Logcat here
java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONArrayorg.json.JSONObject.getJSONArray(java.lang.String)' on a null object reference
at com.example.mind.sqlitedatabase.MainActivity$JSONParse.onPostExecute(MainActivity.java:134)
at com.example.mind.sqlitedatabase.MainActivity$JSONParse.onPostExecute(MainActivity.java:103)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Actually, I faced problem when I click get button to call uri for json parsing.
But when in android device json = null parsing...

Here I used Volley library, it handle the all the things which you did manually(Asynctask, httprequest for json).
I hope it may helps you
// JsonObject request
public void getJSONFromUrl(String url) {
RequestQueue queue = Volley.newRequestQueue(getActivity());
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Response", "Response" + response);
//handle the json response
handleResponse(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error", "Error: " + error.getMessage());
}
});
queue.add(jsonObjReq);
}
// converting from json to Map using JsonHelper class
public void handleResponse(JSONObject response) {
Map<String, Object> map = new HashMap<>();
if(response != null){
try {
// JsonObject to Map
map = JsonHelper.toMap(response);
// boolean isSuccess = map.get("success")
// if(isSuccess){
//}
if (map.size() != 0){
// use the data
}
Log.d("MAp","map" + map);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
here below class will help converting json response to MAP, from map to json.
copied from https://gist.github.com/codebutler/2339666
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.*;
public class JsonHelper {
public static Object toJSON(Object object) throws JSONException {
if (object instanceof Map) {
JSONObject json = new JSONObject();
Map map = (Map) object;
for (Object key : map.keySet()) {
json.put(key.toString(), toJSON(map.get(key)));
}
return json;
} else if (object instanceof Iterable) {
JSONArray json = new JSONArray();
for (Object value : ((Iterable)object)) {
json.put(value);
}
return json;
} else {
return object;
}
}
public static boolean isEmptyObject(JSONObject object) {
return object.names() == null;
}
public static Map<String, Object> getMap(JSONObject object, String key) throws JSONException {
return toMap(object.getJSONObject(key));
}
public static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap();
Iterator keys = object.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
map.put(key, fromJson(object.get(key)));
}
return map;
}
public static List toList(JSONArray array) throws JSONException {
List list = new ArrayList();
for (int i = 0; i < array.length(); i++) {
list.add(fromJson(array.get(i)));
}
return list;
}
private static Object fromJson(Object json) throws JSONException {
if (json == JSONObject.NULL) {
return null;
} else if (json instanceof JSONObject) {
return toMap((JSONObject) json);
} else if (json instanceof JSONArray) {
return toList((JSONArray) json);
} else {
return json;
}
}
}
volley library usage
http://www.androidhive.info/2014/09/android-json-parsing-using-volley/

Related

I have a problem to use Volley. want to use POST method with some parameters and get Array type response but my response is not array type

I have a problem using Volley. want to use POST method with some parameters and get Array type response but my response is not an array type. Here, I share my request code and response.
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest postRequest = new StringRequest(Request.Method.POST, "https://umrahtech.com/umrahtechapi.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
route = null;
route_spinner.setSelection(0);
check_in_date = null;
check_out_date = null;
adults = child = room = child1 = child2 = child3 = child4 = child5 = 0;
text_adults.setText("0 Adult");
text_child.setText("0 Child");
text_room.setText("0 Room");
layout_child.setVisibility(View.GONE);
in_date.setText("Add Date");
out_date.setText("Add Date");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("case", "hotel_makkah");
params.put("location", route);
params.put("check_in_1", check_in_date);
params.put("check_out_1", check_out_date);
params.put("passengers", room_array.toString());
return params;
}
};
queue.add(postRequest);
when u use string request response you get will be string also.
you should turn that response to JsonArray , then get bojects from that JsonArray something like this :
if (response != null) {
JSONArray fetchlist = JSONArray(response);
for (int i=0 ; i<fetchlist .lenght ; i++) {
JSONObject obj = fetchlist.getJSONObject(i);
Int idd = obj.getInt("genderid");
I have solved this question in this way. Where hudx_Object and hudx_JSON is JSONObject
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest hudxconnect = new StringRequest(Request.Method.POST, "https://umrahtech.com/umrahtechapi.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
hudx_Object = new JSONObject(response);
if (hudx_Object != null) {
hudx_JSON = hudx_Object.getJSONObject("response");
hudx_Object = new JSONObject(hudx_JSON.toString());
} else {
hudx_Object = null;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
progressDialog.dismiss();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("case", "hotel_makkah");
params.put("location", route);
params.put("check_in_1", check_in_date);
params.put("check_out_1", check_out_date);
params.put("passengers", room_array.toString());
return params;
}
};

Error initialising a JSONObject from a string

I'm trying to parse JSON from this
string x = "http://www.neowsapp.com/rest/v1/neo/3725762?api_key=DEMO_KEY";
In the browser I can see all the data from this link, but in the parsing method, it can't be converted to a JSONObject.
The error is in this line, in the Utilsul class:
root = new JSONObject(x);
Here is the class containing all the methods for parsing:
public class Utilsul {
private static URL createURL(String x){
URL myurl = null;
try {
myurl = new URL(x);
} catch (MalformedURLException e) {
e.printStackTrace();
}
// Log.i("obtine link ", myurl.toString());
return myurl;
}
private static String raspunsul(URL myurl){
String rasp = "";
HttpURLConnection httpURLConnection = null;
InputStream inputStream = null;
try {
httpURLConnection = (HttpURLConnection) myurl.openConnection();
inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String liniaCurenta = "";
StringBuffer stringBuffer = new StringBuffer();
while ((liniaCurenta = bufferedReader.readLine())!=null){
stringBuffer.append(liniaCurenta);
}
rasp = stringBuffer.toString();
bufferedReader.close();
inputStreamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
httpURLConnection.disconnect();
}
// Log.i("Obtine Raspuns", rasp);
return rasp;
}
private static ArrayList<Obiectul> obtineSir(String x){
ArrayList<Obiectul> sirul = new ArrayList<>();
JSONObject root = null;
try {
root = new JSONObject(x);
// Log.i("Obtine root ", root.toString());
JSONArray sirJONURI = root.getJSONArray("close_approach_data");
for (int i=0; i<sirJONURI.length(); i++){
JSONObject obiectCurent = sirJONURI.getJSONObject(i);
String data = obiectCurent.getString("close_approach_date");
JSONObject jsonViteza = obiectCurent.getJSONObject("relative_velocity");
String viteza = jsonViteza.getString("kilometers_per_hour");
JSONObject jsonDistanta = obiectCurent.getJSONObject("miss_distance");
String distanta = jsonDistanta.getString("kilometers");
sirul.add(new Obiectul(data, viteza, distanta));
}
} catch (JSONException e) {
e.printStackTrace();
}
return sirul;
}
public static ArrayList<Obiectul> toateOdata(String x){
URL ur = createURL(x);
String raspuns = raspunsul(ur);
ArrayList<Obiectul> sir = obtineSir(raspuns);
return sir;
}
}
And here is the class where the parsing will be execute:
public class ActivityB extends AppCompatActivity {
RecyclerView rv;
AdaptorRecycler mAdapter;
ArrayList<Obiectul> sirul;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);
rv = findViewById(R.id.toataLista);
rv.setLayoutManager(new LinearLayoutManager(this));
ClasaAsy clasaAsy = new ClasaAsy();
clasaAsy.execute(linkul());
}
private String linkul(){
String link = "http://www.neowsapp.com/rest/v1/neo/3725762?api_key=DEMO_KEY";
return link;
}
public class ClasaAsy extends AsyncTask<String, Void, ArrayList<Obiectul>>{
#Override
protected ArrayList<Obiectul> doInBackground(String... strings) {
ArrayList<Obiectul> sir = Utilsul.toateOdata(strings[0]);
return sir;
}
#Override
protected void onPostExecute(ArrayList<Obiectul> obiectuls) {
mAdapter = new AdaptorRecycler(ActivityB.this, obiectuls);
rv.setAdapter(mAdapter);
}
}
And here is the Adapter for the RecyclerView (which is tested working, with an ArrayList randomly written).
public class AdaptorRecycler extends RecyclerView.Adapter<AdaptorRecycler.ClasaVH> {
Context context;
ArrayList<Obiectul> sirul;
public AdaptorRecycler(Context context, ArrayList<Obiectul> sirul) {
this.context = context;
this.sirul = sirul;
}
public class ClasaVH extends RecyclerView.ViewHolder{
TextView data, viteza, distanta;
public ClasaVH(#NonNull View itemView) {
super(itemView);
data = itemView.findViewById(R.id.textView2);
viteza = itemView.findViewById(R.id.textView3);
distanta = itemView.findViewById(R.id.textView4);
}
}
#NonNull
#Override
public ClasaVH onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new ClasaVH(LayoutInflater.from(context).inflate(R.layout.randul, parent, false));
}
#Override
public void onBindViewHolder(#NonNull ClasaVH holder, int position) {
Obiectul a = sirul.get(position);
holder.data.setText(a.getData());
holder.viteza.setText(a.getViteza());
holder.distanta.setText(a.getDistanta());
}
#Override
public int getItemCount() {
return sirul.size();
}
}
For some reason, the JSONObject root is never initialised and I couldn't find why.
Please kindly give me an idea, what else should I try.
Thanks

Send data with the JSONObject Volley library to the server with POST method

I want to send a JsonObject with below format to server by using Volley library.
{
"Email":"a#a.a",
"Password":"123456",
"ProveedorAcceso":"web",
"NivelAcceso":{
"Id": 1
},
"Estatus": {
"Id":1
} }
My code:
public void getData() {
StringRequest postRequest = new StringRequest(Request.Method.POST, urlLogin,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
Log.d(TAG, String.valueOf(jsonResponse));
} catch (JSONException e) {
e.printStackTrace();
Log.d(TAG, String.valueOf(e));
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
try {
String responseBody = new String(volleyError.networkResponse.data, "utf-8");
JSONObject jsonObject = new JSONObject(responseBody);
/**
dialogLoading.dismiss();
if (jsonObject.getInt("Codigo") == 400) {
onDialogErrorResponse();
}**/
} catch (JSONException e) {
//Handle a malformed json response
Log.d("Response", String.valueOf(e));
} catch (UnsupportedEncodingException error) {
Log.d("Response", String.valueOf(error));
}
}
}
) {
// here is params will add to your url using post method
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("Email", edtEmail.getText().toString());
params.put("Password", edtPassword.getText().toString());
params.put("ProveedorAcceso", "web");
params.put("NivelAcceso", 1+"");
params.put("Estatus", 1+"");
return params;
}
};
postRequest.setRetryPolicy(new DefaultRetryPolicy(
10000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(postRequest);
DiskBasedCache cache = new DiskBasedCache(this.getCacheDir(), 500 * 1024 * 1024);
requestQueue = new RequestQueue(cache, new BasicNetwork(new HurlStack()));
requestQueue.start();
}
As the server does not receive the data correctly it throws me an error with reference to the data.
"Codigo":500,"Mensaje":"Object reference not set to an instance of an object."
I hope you can help me in this doubt, since I am very confused about it, thank you very much.

passing arraylist item of tabfragment recyclerview to other activity recyclerview

I have fetched JSonarray data as string and have added it to arraylist i.e
this is done on a tab fragment recycler view .
JSONObject jsonObject = response.getJSONObject(index);
// Log.d("TAG", jsonObject.getString("title"));
int id =jsonObject.getInt("id");
String title=jsonObject.getString("title");
// Log.d("TAG", jsonObject.getString("description"));
String shortDec=jsonObject.getString("description");
String longDec=jsonObject.getString("short_description");
String imguUrl=jsonObject.getString("image");
String createdAt=jsonObject.getString("created_at");
// Toast.makeText(NewsDetailsActivity.this, "\nTitle: "+title+"\n Description:", Toast.LENGTH_SHORT).show();
NewsListGetter newsListGetter=new NewsListGetter(id, title, shortDec,longDec,imguUrl,createdAt);
arrayList.add(newsListGetter);
adapter.notifyDataSetChanged();
I have another activity called NewsDetailsAcivity,in which I have implemented a recycler view.
I want to pass only the data from recylerview of tab1fragment which is clicked,to the newsDetailActivity recylerview.
Your response is already in JSONArray no need to store in another JSON Array.
Look at the code below.
RequestQueue requestQueue = Volley.newRequestQueue(this);
String url = "http://ec2-54-147-238-136.compute-1.amazonaws.com/hmc/api/getnewsfeeds?order=asc";
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int index = 0; index < response.length(); index++) {
try {
JSONObject jsonObject = response.getJSONObject(index);
Log.d("TAG", jsonObject.getString("title"));
Log.d("TAG", jsonObject.getString("description"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(request);
Take Your Response.Listener in String first like
new Response.Listener<String>
Then Store your response in JSONObject, and then get JSONArray from stored JSONObject. Like this:
JSONObject data = new JSONObject(response);
JSONArray responseArray = data.getJSONArray("data"); // here data is Key of your JsonArray.
Hope this helps you!
As per your JSON Response You can paste this code. I tasted this on my machine and working, Let me know if any issue is there
String json_url = "http://ec2-54-147-238-136.compute-.amazonaws.com/hmc/api/getnewsfeeds?order=asc";
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jObj = response.getJSONObject(i);
Log.d("TAG", jObj.getString("title"));
Log.d("TAG", jObj.getString("description"));
} catch (JSONException exc) {
exc.printStackTrace();
}
}
}
}
How to save data in ArrayList
Create SampleModelClass
public class SampleModelClass {
private String id;
private String description;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
Now in your activity Where you are parsing JSON, Do the Same
JSONArray root_array = root_obj.getJSONArray("YOUR_ARRAY_NODE_NAME");
for (int i = 0; i < root_array.length(); i++) {
SampleModelClass commonModels = new SampleModelClass();
JSONObject array_object = root_array.getJSONObject(i);
commonModels.setId(array_object.optString("id"));
commonModels.setDescription("description");
common_stop_list.add(commonModels);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();

i unable to convert JSObject of API key

i am using the APi of https://openweathermap.org/current
i want to get particular weather part from the API as below my code so i am using JSON
Here below link is API key where i want weather part
http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b1b15e88fa797225412429c1c50c122a1
Value null of type org.json.JSONObject$1 cannot be converted to JSONObject
I am using the AsyncTask
My MainActivity is here
public class MainActivity extends AppCompatActivity {
String data ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadWeatherData downloadWeatherData = new DownloadWeatherData();
try {
downloadWeatherData.execute("http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b1b15e88fa797225412429c1c50c122a1").get();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here is my java file
public class DownloadWeatherData extends AsyncTask {
String weatherdata;
#Override
protected String doInBackground(String... urls)
{
try {
URL url = new URL(urls[0]);
HttpURLConnection connection =(HttpURLConnection) url.openConnection();
connection.connect();
InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream());
int data = inputStreamReader.read();
while(data!=-1)
{
char str = (char)data;
weatherdata+=str;
data = inputStreamReader.read();
}
return weatherdata;
}
catch (MalformedURLException e)
{
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s)
{
super.onPostExecute(s);
try {
JSONObject jsonObject = new JSONObject(s);
String info = jsonObject.getString("weather");
Log.d("weatherpart",info);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
You are doing it wrong. Weather is an array not a json object. Do it like this:
JSONObject jsonObj = new JSONObject(s);
JSONArray ja_data = jsonObj.getJSONArray("weather");
int length = ja_data.length();
for(int i=0; i<length; i++) {
JSONObject jsonObj = ja_data.getJSONObject(i);
.
.
.
}