Here my json file: settings.json (in assets folder):
{
"settings": [
{
"level": "upper"
}
]
}
I working in Android Studio. I print the upper word in a TextView from the json file, but this not working, my app is crashed. Ideas?
my code in java file:
public class MainActivity extends AppCompatActivity {
ArrayList<String> level = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONArray userArray = obj.getJSONArray("settings");
for (int i = 0; i < userArray.length(); i++) {
JSONObject userDetail = userArray.getJSONObject(i);
level.add(userDetail.getString("level"));
}
} catch(JSONException e){
e.printStackTrace();
}
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(level.get(0));
setContentView(R.layout.activity_main);
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("settings.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;
}
Thank you.
Android, json, source code...
And why the else working in the if function? The level's record is upper. Why not true the if?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
// get JSONObject from JSON file
JSONObject obj = new JSONObject(loadJSONFromAsset());
// fetch JSONArray named users
JSONArray userArray = obj.getJSONArray("settings");
// implement for loop for getting users list data
for (int i = 0; i < userArray.length(); i++) {
// create a JSONObject for fetching single user data
JSONObject userDetail = userArray.getJSONObject(i);
// fetch email and name and store it in arraylist
level.add(userDetail.getString("level"));
}
} catch(JSONException e){
e.printStackTrace();
}
TextView textView = (TextView) findViewById(R.id.textView);
if (level.get(0) == "upper") {
textView.setText(level.get(0));
} else {
}
I hope this will work for you,
Write Your onCreate() method like this,
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONArray userArray = obj.getJSONArray("settings");
for (int i = 0; i < userArray.length(); i++) {
JSONObject userDetail = userArray.getJSONObject(i);
level.add(userDetail.getString("level"));
}
} catch(JSONException e){
e.printStackTrace();
}
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(level.get(0));
}
set setContentView() method first then initialize your textview.In your code you accessing text view before layout initialized.
Related
The Layout that I am getting
public class MainActivity extends AppCompatActivity {
TableLayout tableLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tableLayout = findViewById(R.id.tableLayout);
try{
JSONObject jsonObject = new JSONObject(loadJson());
JSONObject jsonObject1 = jsonObject.getJSONObject("data");
JSONArray jsonArray = jsonObject1.getJSONArray("application_step");
JSONArray sections = jsonArray.getJSONObject(0).getJSONArray("section");
for(int i = 0;i<sections.length();i++)
{
TableRow tr = new TableRow(this);
JSONArray fields = sections.getJSONObject(i).getJSONArray("fields");
for(int j = 0;j<fields.length();j++)
{
Button button = new Button(this);
button.setText("Button"+j);
tr.addView(button);
}
tr.setFitsSystemWindows(true);
//tr.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.FILL_PARENT));
tableLayout.addView(tr);
}
}
catch (Exception e){
Log.d("ErrorTest ",e.getMessage());
}
}
public String loadJson(){
String json=null;
try{
InputStream io = MainActivity.this.getAssets().open("BaseUrlJson.json");
int size = io.available();
byte buffer[] = new byte[size];
io.read(buffer);
io.close();
json = new String(buffer,"UTF-8");
}
catch (Exception e){
Log.d("Error: ",e.getMessage());
return null;
}
return json;
}
}
The code above gets me the layout from a JSON config file.
I want all the rows to be of same length by expanding the cells(column wise) in the rows which are shorter.
I am generating it dynamically.
i think You should check this adaptable layout from here.
https://github.com/Cleveroad/AdaptiveTableLayout
I have a problem with this Json file. I am trying to do a Parser that shows in a textview the results after a button is pressed. I wonna parse the "firstName" tag but to do this, I need to pass through the others tags like "league" and "standard". I don't know how to parse them in this Json file.
The Json file is structured like this:
{
"_internal":{
"pubDateTime":"2017-06-23 03:21:52.076",
"xslt":"xsl/league/roster/marty_active_players.xsl",
"eventName":"league_roster"
},
"league":{
"standard":[
{
"firstName":"Alex",
"lastName":"Abrines",
"personId":"203518",
"teamId":"1610612760 1610612760",
"jersey":"8",
"pos":"G-F",
"heightFeet":"6",
"heightInches":"6",
"heightMeters":"1.98",
"weightPounds":"190",
"weightKilograms":"86.2",
"dateOfBirthUTC":"1993-08-01",
"teams":[
{
"teamId":"1610612760",
"seasonStart":"2016",
"seasonEnd":"2016"
}
],
"draft":{
"teamId":"1610612760",
"pickNum":"32",
"roundNum":"2",
"seasonYear":"2013"
},
"nbaDebutYear":"2016",
"yearsPro":"0",
"collegeName":"",
"lastAffiliation":"Spain/Spain",
"country":"Spain"
},
This is my Java code:
public class MainActivity extends AppCompatActivity {
Button btnHit;
TextView txtJson;
ProgressDialog pd;
String Players[] = new String[100];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnHit = (Button) findViewById(R.id.btn);
txtJson = (TextView) findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonTask().execute("http://data.nba.net/10s/prod/v1/2016/players.json");
}
});
}
private class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line); //here u ll get whole response...... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
String DataPlayers = jsonObject.getString("standard");
JSONArray jsonArray = new JSONArray(DataPlayers);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject JO = jsonArray.getJSONObject(i);
Players[i] = JO.getString("firstName");
txtJson.append(Players[i] + "\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
if (pd.isShowing()) {
pd.dismiss();
}
}
}
Wrong:
JSONObject jsonObject = new JSONObject(result);
String DataPlayers = jsonObject.getString("standard");
Correct:
JSONObject jsonObject = new JSONObject(result);
JsonObject objStandard = jsonObject.getJSONObject("league");
Now from objStandard object, you can retrieve the json array and iterate through the sub json objects.
JSONArray jsonArray = objStandard.getJSONArray("standard");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject JO = jsonArray.getJSONObject(i);
Players[i] = JO.getString("firstName");
txtJson.append(Players[i] + "\n");
}
2 cents suggestion :)
It seems you have just started exploring android development, saying based on you are using a legacy method of json parsing, I would suggest you to check out GSON library, which is a Java serialization/deserialization library to convert Java Objects into JSON and back. In short, you will not be needed to parse JSON response manually but rather you will be having normal java class objects and members/methods to deal with.
Your code should be like this
try {
String result = "your_json_string";
JSONObject jsonObject = new JSONObject(result);
JSONObject leagueObject = jsonObject.getJSONObject("league");
JSONArray standardArray = leagueObject.getJSONArray("standard");
for (int i = 0; i < standardArray.length(); i++) {
JSONObject standardObject = standardArray.getJSONObject(i);
String name = standardObject.getString("firstName");
}
} catch (Exception e) {
System.out.println(e);
}
I am getting the following error:
This is my source code:
package com.example.arpok.iomatic;
LineGraphSeries<DataPoint> series;
ArrayList<HashMap<String, String>> arrayListData;
public static String data;
TextView graphOneTV,graphTwoTV,graphThreeTV;
GraphView graph;
String x,y;
public Graph_Fragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_graph_, container, false);
}
HttpURLConnection connection;
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
graphOneTV = (TextView) getView().findViewById(R.id.TVGraph1);
graphTwoTV = (TextView) getView().findViewById(R.id.TVGraph2);
graphThreeTV = (TextView) getView().findViewById(R.id.TVGraph3);
graph = (GraphView) getView().findViewById(R.id.graph1);
graphDataClass gdc = new graphDataClass();
gdc.execute();
}
public class graphDataClass extends AsyncTask<String ,String ,String>
{
#Override
protected String doInBackground(String... strings) {
try {
URL url = new URL("http://192.168.1.34/getGraphData.php?");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while(line != null)
{
line = bufferedReader.readLine();
data = data + line;
}
JSONObject jo = new JSONObject(data);
for(int i=0;i<data.length();i++) {
x = jo.getString("twitter");
y = jo.getString("googleplus");
System.out.print("x: "+x+"y: "+y);
HashMap<String, String> tempHashMapData = new HashMap<>();
tempHashMapData.put("twitter",x);
tempHashMapData.put("googleplus",y);
arrayListData.add(tempHashMapData);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPreExecute()
{
super.onPreExecute();
}
protected void onPostExecute(String s )
{
super.onPostExecute(s);
graphOneTV.setText(data);
}
}}
The above code is the fragment in which I need to fetch the data form the JSON and plot it on the graph. The thing is when I am displaying the "data" named variable which is having the JSON data on a textView then it is showing properly but when I am assigning the same "data" variable to the JSONObject then the above error occurs.
This is my Json data which i need to plot on the Line Graph
[{"twitter":"200","googleplus":"60"},{"twitter":"150","googleplus":"180"},{"twitter":"90","googleplus":"120"}]
Someone please tell me how can I fetch the JSON data and parse it and plot it on a line graph.
try this one.
JSONArray jsonarray = new JSONArray(jsonStr);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
x = jo.getString("twitter");
y = jo.getString("googleplus");
System.out.print("x: "+x+"y: "+y);
HashMap<String, String> tempHashMapData = new HashMap<>();
tempHashMapData.put("twitter",x);
tempHashMapData.put("googleplus",y);
arrayListData.add(tempHashMapData);
}
Try this way
ArrayList<HashMap<String, String>> arrayListSocial = new ArrayList<>();
String string = "[{\"twitter\":\"200\",\"googleplus\":\"60\"},{\"twitter\":\"150\",\"googleplus\":\"180\"},{\"twitter\":\"90\",\"googleplus\":\"120\"}]";
try {
JSONArray jsonarray = new JSONArray(string);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String socailTwiter= jsonobject.getString("twitter");
String socailGplus = jsonobject.getString("googleplus");
Log.e("socailTwiter",socailTwiter);
HashMap<String, String> hashMap = new HashMap<>();
hashMap .put("twitter",socailTwiter);
hashMap .put("googleplus",socailGplus );
arrayListSocial.add(hashMap);
}
}catch (Exception e){
e.printStackTrace();
}
I am trying to extract some data from a json array file, i followed the steps from
Reading a Json Array in android
a snippit of the json array:
[
{
"JobNo": 1,
"JobTime": 30,
"JobDate": "20170911",
"WorkerTime": 27,
"JobTimeError": -3
},
{
"JobNo": 2,
"JobTime": 22,
"JobDate": "20170911",
"WorkerTime": 21,
"JobTimeError": -1
},
What i want to be able to do is, extract the data and store them into their own arrays, JobNo to JobNo array, etc. the following code is my attempt, but it doesn't store the values (crashes at toast because it says no data in array).
thanks
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner staticSpinner = (Spinner) findViewById(R.id.static_spinner);
ArrayList<Integer> JobNo = new ArrayList<>();
ArrayList<Integer> JobTime= new ArrayList<>();
ArrayList<String> JobDate= new ArrayList<>();
ArrayList<Integer> WorkerTime= new ArrayList<>();
ArrayList<Integer> JobTimeError = new ArrayList<>();
try {
JSONObject json = new JSONObject(loadJSONFromAsset());
JSONArray jArray = json.getJSONArray("Data");
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
int JobN = json_data.getInt("JobNo");
int JobT = json_data.getInt("JobTime");
String JobD = json_data.getString("JobDate");
int WorkT = json_data.getInt("WorkerTime");
int JobTE = json_data.getInt("JobTimeError");
JobNo.add(JobN);
JobTime.add(JobT);
JobDate.add(JobD);
WorkerTime.add(WorkT);
JobTimeError.add(JobTE);
}
}
catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(this,
JobDate.get(1),
Toast.LENGTH_LONG).show();
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("convertcsv.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;
}
Your JSON String is not a JSON object, it is a JSON Array, So use:
JSONArray jArray = new JSONArray (loadJSONFromAsset());
I want to add json to listview,
but I have no idea
I list items with listview like that;
public class ListSectionActivity extends Activity {
private AndroidListAdapter list_adapter;
private ListView lv_android;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_section);
DataCollection.data_arr=new ArrayList<DataCollection>();
DataCollection.data_arr.add(new DataCollection("apple"));
DataCollection.data_arr.add(new DataCollection("car"));
lv_android=(ListView)findViewById(R.id.lv_android);
list_adapter=new AndroidListAdapter(ListSectionActivity.this, R.layout.list_item,DataCollection.data_arr);
ListSeparateAdapter<DataCollection> listsectionAdapter = new ListSeparateAdapter<DataCollection>(ListSectionActivity.this,
list_adapter, R.layout.enroll_section_list, R.id.tv_section);
lv_android.setAdapter(listsectionAdapter);
}
}
but I want to list item from json.
my json code:
#Override
protected void onPostExecute(String content) {
try {
JSONObject jsonObject = new JSONObject(content);
JSONArray jsonArray = jsonObject.getJSONArray("main");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
JSONArray server = c.getJSONArray("home");
for(int j=0; j<server.length(); j++){
JSONObject serverObject = server.getJSONObject(j);
string rank = serverObject.getString("rank");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
my json;
{
"main":[
{
"home":[
{"rank":"33"},
{"rank":"72"},
{"rank":"49"}
]
}
]
}
I want to add "string rank" to my listview.
How can I do that?
Thanks.
Edit: I could add json to listview but I can only list first json item. my new code
public class ListSectionActivity extends Activity {
private AndroidListAdapter list_adapter;
private ListView lv_android;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_section);
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute("url");
}
});
}
class ReadJSON extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
try {
JSONObject jsonObject = new JSONObject(content);
JSONArray jsonArray = jsonObject.getJSONArray("main");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
JSONArray server = c.getJSONArray("home");
for(int j=0; j<server.length(); j++){
JSONObject serverObject = server.getJSONObject(j);
String rank = serverObject.getString("rank");
DataCollection.data_arr=new ArrayList<DataCollection>();
DataCollection.data_arr.add(new DataCollection(rank));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
lv_android=(ListView)findViewById(R.id.lv_android);
list_adapter=new AndroidListAdapter(ListSectionActivity.this, R.layout.list_item,DataCollection.data_arr);
ListSeparateAdapter<DataCollection> listsectionAdapter = new ListSeparateAdapter<DataCollection>(ListSectionActivity.this,
list_adapter, R.layout.enroll_section_list, R.id.tv_section);
lv_android.setAdapter(listsectionAdapter);
}
}
private static String readURL(String theUrl) {
StringBuilder content = new StringBuilder();
try {
URL url = new URL(theUrl);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
content.append(line + "\n");
}
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
}
return content.toString();
}
}
DataCollection
public class DataCollection {
public String name;
public static ArrayList<DataCollection> data_arr=null;
public DataCollection(String name){
this.name=name;
}
}
UPDATED: You can do this inside your onPostexecute. Save the rank array inside a listview and use it inside your adapter.
protected void onPostExecute(String content) {
DataCollection.data_arr=new ArrayList<DataCollection>();
try {
JSONObject jsonObject = new JSONObject(content);
JSONArray jsonArray = jsonObject.getJSONArray("main");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
JSONArray server = c.getJSONArray("home");
for(int j=0; j<server.length(); j++){
JSONObject serverObject = server.getJSONObject(j);
String rank = serverObject.getString("rank");
DataCollection.data_arr.add(new DataCollection(rank));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
if(!data_arr.isEmpty()){
//you can set the adapter and listview here. Something like this
your_list_adapter=new AndroidListAdapter(this, R.layout.list_item,data_arr);
your_lv_android.setAdapter(list_adapter);
}
}