I have the following code to retrieve Json from raw file:
#Override
protected RecyclerView.Adapter getAdapter() {
if (adapter == null) {
String jsonStr = readRawFile();
Gson gson = new Gson();
VideoPage videoPage = gson.fromJson(jsonStr, VideoPage.class);
adapter = new VideoAdapter(videoPage);
}
return adapter;
}
String readRawFile() {
String content = "";
Resources resources = getContext().getResources();
InputStream is = null;
try {
is = resources.openRawResource(R.raw.video_list);
byte buffer[] = new byte[is.available()];
is.read(buffer);
content = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return content;
}
File video_list.json : enter image description here
"data": [
{
"title": "Video 1",
"imgUrl": "http://example.com/",
"videoUrl": "http://example.com/",
"docUrl": "http://example.com/"
},
{
"title": "Video 2",
"imgUrl": "http://example.com//",
"videoUrl": "http://example.com/",
"docUrl": "http://example.com/"
},
Now I do not want to get Json from this video_list file, I want to get the Json file from an url containing Json. Can someone help me code again?
Related
I want to parse JSON from local file stored in asset folder and set it to recyclerview in android. But recyclerview is not populating.
Can anyone please tell me whats wrong with this?
I have tried many answers from here, but its not working.
JSON
{
"box": [
{
"text" : "text1 "
},
{
"text" : "text2"
},
{
"text" : "text3"
},
...............
]
}
CODE
private String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("file.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
private void RequestJson() {
recyclerView = findViewById(R.id.mRecycler);
List<Box> data=new ArrayList<>();
try {
JSONObject json = new JSONObject(loadJSONFromAsset());
JSONArray tablelist = json.getJSONArray("box");
for (int i = 0; i < tablelist.length(); i++) {
JSONObject AllTable = tablelist.getJSONObject(i);
Box items2 = new Box();
items2.setText(AllTable.getString("text"));
data.add(items2);
}
mAdapter = new BoxAdapter(MainActivity.this, data);
recyclerView.setAdapter(mAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
change this things. and make sure data not empty.
mAdapter = new BoxAdapter(MainActivity.this, data);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
recyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
I try to get information from this link
and I don't get it !
This is my code:
String s = getJSONFile();
String myDataArray[] = {};
try{
JSONObject reportJSON = new JSONObject();
JSONArray dateJSON = reportJSON.getJSONArray("terrestrial_date");
myDataArray = new String[dateJSON.length()];
for (int i = 0; i <dateJSON.length(); i++){
JSONObject jsonObject = dateJSON.getJSONObject(i);
myDataArray[i] = jsonObject.getString("terrestrial_date");
}
}catch (JSONException e){
e.printStackTrace();
}
ArrayAdapter<String> stringAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.row, myDataArray);
if (mListView != null){
mListView.setAdapter(stringAdapter);
}
}
this is the getJSONFile method:
public String getJSONFile() {
String json = null;
try {
InputStream is = getResources().openRawResource(R.raw.weather_json);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
Thanks for help :)
You should use GSON librari and for the Model of this code http://www.jsonschema2pojo.org/
This is so easy.
terrstial_date is a String of report. try this,
String date=jsonObject.getString("terestial_date");
also your json parsing structere is not correct accroding to your json
{
"report": {
"terrestrial_date": "2017-10-13",
"sol": 1844,
"ls": 73.0,
"min_temp": -81.0,
"min_temp_fahrenheit": -113.8,
"max_temp": -28.0,
"max_temp_fahrenheit": -18.4,
"pressure": 869.0,
"pressure_string": "Higher",
"abs_humidity": null,
"wind_speed": null,
"wind_direction": "--",
"atmo_opacity": "Sunny",
"season": "Month 3",
"sunrise": "2017-10-13T10:59:00Z",
"sunset": "2017-10-13T22:43:00Z"
}
}
This is how you can get response from OkHttp
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://marsweather.ingenology.com/v1/latest/?format=json")
.get()
.build();
try {
Response response = client.newCall(request).execute();
String json = response.body().string();
JSONObject jsonObject = new JSONObject(json);
JSONObject reportJson = jsonObject.getJSONObject("report"); // your report object.
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
Put your Json file in your assets folder with .json extension and use this method to get JsonString from it
public String loadJSONFromAsset(String fileName) {
String json = null;
try {
InputStream is = getAssets().open(fileName);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
And get the String using this function like this
String jsonString = MyApplication.loadJSONFromAsset(this,"yourJsonFileName.json");
and Parse like that
try{
JSONObject responce = new JSONObject(jsonString);
JSONArray report= responce.getJSONObject("report");
String terrestrial_date = report.getString("terrestrial_date");
}catch (JSONException e){
e.printStackTrace();
}
this is my code after all the change:
public void find_weather() {
String url = "http://marsweather.ingenology.com/v1/latest/?format=json";
JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject main_object = response.getJSONObject("results");
JSONArray array = response.getJSONArray("");
JSONObject object = array.getJSONObject(0);
String date = object.getString("date");
String tempMin = String.valueOf(main_object.getDouble("min_temp"));
String tempMax = String.valueOf(main_object.getDouble("max_temp"));
String atmo_opacity = object.getString("atmo_opacity");
mMaxTemp.setText("max_temp");
mMinTemp.setText("min_temp");
mAtmoOpacity.setText("atmo_opacity");
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEEE-MM-dd");
String formatted_data = sdf.format(calendar.getTime());
mDate.setText(formatted_data);
double temp_max_int = Double.parseDouble(tempMax);
double temp_min_int = Double.parseDouble(tempMin);
mMaxTemp.setText(String.valueOf(i));
mMinTemp.setText(String.valueOf(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(jor);
You are doing in wrong way
1.report is a JsonObject inside your response means you have your report inside another JsonObject. First you have to parse your response to get report data
2.terrestrial_date is a string data so you have to use report.getJsonString("terrestrial_date") you are using reportJSON.getJSONArray("terrestrial_date"); which is used for Array data
For, more information get a look here How to parse JSON in Android
Try this,
String s = getJSONFile();
String terrestrial_date = "";
try{
JSONObject responce = new JSONObject(s);
JSONObject report= responce.getJSONObject("report");
terrestrial_date = report.getString("terrestrial_date");
}catch (JSONException e){
e.printStackTrace();
}
EDIT
Try, Volley for fetching JSON data
First you need to add dependency of volley in build.gradle file-:
dependencies {
compile 'com.android.volley:volley:1.0.0'
}
Then use following code to fetch or parse your JSON data
// Tag used to cancel the request
String url = "http://marsweather.ingenology.com/v1/latest/?format=json";
StringRequest strReq = new StringRequest(Request.Method.GET,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
String terrestrial_date = "";
try{
JSONObject responce = new JSONObject(response);
JSONObject report= responce.getJSONObject("report");
terrestrial_date = report.getString("terrestrial_date");
}catch (JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to request queue
Volley.newRequestQueue(this).add(strReq);
SCREENSHOT
As, You can see the screenshot above. I am getting response with the same code
I'm having trouble loading objects from an JSON file, the idea is to store objects in the JSON file and return an array of objects, is there any easier way doing this? Or is there any better solution than JSON for doing this?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_list);
TextView studentlistTextView = (TextView)findViewById(R.id.studentlistTextView);
ArrayList<students> studentArray = loadJSONFromAsset();
try {
studentlistTextView.setText(studentArray.get(0).getName());
}catch(Exception e){
e.printStackTrace();
}
}
public ArrayList<students> loadJSONFromAsset() {
ArrayList<students> studentArray = new ArrayList<>();
String json = null;
try {
InputStream is = getAssets().open("jsonstudent");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
try {
JSONObject obj = new JSONObject(json);
JSONArray m_jArry = obj.getJSONArray("students");
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
students student = new students();
student.setName(jo_inside.getString("name"));
student.setLastname(jo_inside.getString("lastname"));
student.setNumber(jo_inside.getString("number"));
studentArray.add(student);
}
} catch (JSONException e) {
e.printStackTrace();
}
return studentArray;
}
}
This is my JSON file
{ "student" : [
{"name" : "hans", "lastname" : "rosenboll", "number" : "5325235" }
]}
You can use Gson and Shared Preference to store objects in the JSON file and return an array of objects:
private final String PERSONAL_INFO = "personal_info";
public void putPersonalInfo(Profile info) {
Gson gson = new Gson();
String json = gson.toJson(info);
getAppPreference().edit().putString(PERSONAL_INFO, json).commit();
}
public Profile getPersonalInfo() {
Gson gson = new Gson();
return gson.fromJson(getAppPreference().getString(PERSONAL_INFO, null), Profile.class);
}
I am getting problem to parse json in android spinner. I have tried by below listed code but I am getting full json array in spinner like screenshot
My Json Array
{"Department":[{"1":"Computer"},{"2":"IT"},{"3":"Civil"}]} // like this type json string
My Code
public class GetDropdownItems extends AsyncTask<Void, Void, String[]> {
public GetDropdownItems() {
super();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.i("MY_NETWORK", "first");
}
#Override
protected String[] doInBackground(Void... params) {
StringBuilder sbstaffdep = new StringBuilder();
String staffdepURL = StaticDataEntity.URL_GETDEP;
String charset = "UTF-8"; // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name()
URLConnection connectionstaffDep = null;
try {
connectionstaffDep = new URL(staffdepURL).openConnection();
} catch (IOException e) {
e.printStackTrace();
}
connectionstaffDep.setDoOutput(true); // Triggers POST.
connectionstaffDep.setRequestProperty("Accept-Charset", charset);
connectionstaffDep.setConnectTimeout(6000);
InputStream responsestaffDep = null;
try {
responsestaffDep = connectionstaffDep.getInputStream();
} catch (IOException e) {
e.printStackTrace
();
return new String[]{"unreachable"};
}
BufferedReader brstaffDep = new BufferedReader(new InputStreamReader(responsestaffDep));
String readstaffDep;
try {
while ((readstaffDep = brstaffDep.readLine()) != null) {
//System.out.println(read);
sbstaffdep.append(readstaffDep);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
brstaffDep.close();
} catch (IOException e) {
e.printStackTrace();
}
String[] finaldata = new String[1];
finaldata[0] = sbstaffdep.toString();
return finaldata;
}
#Override
protected void onPostExecute(String[] s) {
super.onPostExecute(s);
if (s[0].equals("unreachable")) {
new SweetAlertDialog(SignUpStaff.this, SweetAlertDialog.ERROR_TYPE)
.setTitleText("Oops...")
.setContentText("Unable to connect to server ! \n Please try again later.")
.setCancelText("Ok")
.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
sweetAlertDialog.cancel();
}
})
.show();
return;
}
Log.i("MY_NETWORK", s.toString());
String[] dataofdropdowndep = s[0].split(",");
ArrayAdapter<String> adapterdep = new ArrayAdapter<String>(SignUpStaff.this, android.R.layout.simple_list_item_1, dataofdropdowndep);
adapterdep.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dropstaffdep.setAdapter(adapterdep);
}
}
public class GetDropdownItems extends AsyncTask<Void, Void, String> {
public GetDropdownItems() {
super();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.i("MY_NETWORK", "first");
}
#Override
protected String doInBackground(Void... params) {
StringBuilder sbstaffdep = new StringBuilder();
String staffdepURL = StaticDataEntity.URL_GETDEP;
String charset = "UTF-8"; // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name()
URLConnection connectionstaffDep = null;
try {
connectionstaffDep = new URL(staffdepURL).openConnection();
} catch (IOException e) {
e.printStackTrace();
}
connectionstaffDep.setDoOutput(true); // Triggers POST.
connectionstaffDep.setRequestProperty("Accept-Charset", charset);
connectionstaffDep.setConnectTimeout(6000);
InputStream responsestaffDep = null;
try {
responsestaffDep = connectionstaffDep.getInputStream();
} catch (IOException e) {
e.printStackTrace
();
return "unreachable";
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
responsestaffDep, "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();
Log.d("-------------", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return json;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s.equals("unreachable")) {
new SweetAlertDialog(SignUpStaff.this, SweetAlertDialog.ERROR_TYPE)
.setTitleText("Oops...")
.setContentText("Unable to connect to server ! \n Please try again later.")
.setCancelText("Ok")
.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
sweetAlertDialog.cancel();
}
})
.show();
return;
}
Log.i("MY_NETWORK", s.toString());
Json js=new Json(s);
JSONArray array=js.getJSONArray("Department");
for(JSONArray b:array){
// traverse array here
}
ArrayAdapter<String> adapterdep = new ArrayAdapter<String>(SignUpStaff.this, android.R.layout.simple_list_item_1, dataofdropdowndep);
adapterdep.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dropstaffdep.setAdapter(adapterdep);
}
}
HI Change your Json Response from server or you can change manually .
Here is your format :
{"Department"
[
{
"1": "Computer"
},
{
"2": "IT"
},
{
"3": "Civil"
}
]
}
Please check it with any json viewer format online.
this type json data:
check this json array:
{
"schools": [{
"Name": "Hill View Elementary",
"SchoolID": "HVE"
}, {
"Name": "Mill View",
"SchoolID": "MVE"
}, {
"Name": "Big School",
"SchoolID": "BSC"
}]
}
your mistake is you are not putting comma between two objects
The way you are fetching the Json file is wrong, there is already Json classes that can easly get each array,object or key alone.
org.json is the library we are going to use with the JSONArray and JSONObject classes.
Before we start you should know a basic understanding of the Json file scheme :
"name":{} this is the array syntax represented by the {} symbols, this array can hold arrays,objects or keys.
[] represent and object which can hold arrays and keys too but it doesn't have name.
"key":"value" now the is key type which can hold the data or values you want and has a key to retrieve it by name.
Now here is a piece of code to fetch your file and get each part of the Json file alone and then you can populate it as you wish.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.res.Resources;
public class Fetch {
final private static String DEPARTMENT = "Department";
String [] departments ;
public void fetch(Resources r , int resourceID) {
String JsonString = readStringFromRaw(r, resourceID);
//the whole josn file is a json object even if it starts with { and ends with } so...
try {
JSONObject mainObject = new JSONObject(JsonString);
// the JSONObject throws a JSONException if there is something wrong with the syntax
JSONArray department = mainObject.getJSONArray(DEPARTMENT);
int length = department.length();
departments = new String[length];
JSONObject object;
for(int i = 0 ; i < length ; i++){
object = department.getJSONObject(i);
departments[0] = object.getString(""+i+1);
//this because you tagged the keys with 1 , 2 , 3 and so on.. so it has the value of the object that it is in + 1 .
//the reason I put "" empty quotations is because I want it a string so this is a way to cast the numbers to strings .
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public static String readStringFromRaw(Resources r, int resourceID) {
InputStream is = r.openRawResource(resourceID);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder(1000);
String line;
try {
while ((line = br.readLine()) != null)
sb.append(line);
br.close();
is.close();
return sb.toString();
} catch (IOException e) {
return e.getMessage();
}
}
}
With this class you can get a String array holding the departments you want for your json file that you have.
The heirarchy between arrays and objects is very important so keep in mind that when you write a json file make it less complicated to extract the information easier.
I don't know how to do after this to convert my Java to JSON with Jackson
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ObjectMapper mapper = new ObjectMapper();
Book b = new Book();
ArrayList<Book> listBook = new ArrayList<Book>();
listBook.add(b);
b = new Book();
b.setName("exam");
b.setFileName("res/raw/exam.txt");
b.setCate(0); //4 categories here
b.setSoundFileName("res/raw/exams.mp3");
b.setTranFileName("res/raw/examt.txt");
listBook.add(b);
b = new Book();
b.setName("test");
b.setCate(0);
b.setFileName("res/raw/test.txt");
b.setSoundFileName("res/raw/tests.mp3")
b.setTranFileName("res/raw/textt.txt");
String jsonString = "";
try {
jsonString = mapper.writeValueAsString(listBook);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.d("ttt", "show ans : "+jsonString);
How do I do next to write this to my SD card?
as user Zain has told, Gson is more convenient to use, However, assuming that you are getting the Json string from this line:
jsonString = mapper.writeValueAsString(listBook);
Then use this method to write the string to a file in sdcard.
public static void writeStringToFile(String p_string, String p_fileName)
{
FileOutputStream m_stream = null;
try
{
m_stream = new FileOutputStream(p_fileName);
m_stream.write(p_string.getBytes());
m_stream.flush();
}
catch (Throwable m_th)
{
Log.e(TAG + " Error in writeStringToFile(String p_string, String p_fileName) of FileIO", m_th);
}
finally
{
if (m_stream != null)
{
try
{
m_stream.close();
}
catch (Throwable m_e)
{
Log.e(TAG + " Error in writeStringToFile(String p_string, String p_fileName) of FileIO", m_e);
}
m_stream = null;
}
}
}