Customizing Table Layout in android - android

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

Related

Print a json file in textView

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.

JSON Parser Error :Value null of type org.json.JSONObject$1 cannot be converted to JSONObject

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

unable to save data from json array

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

Android add JSON to <string>

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

Refresh data in ListFragment

I want to get data from php, then show in listview. But I do not know not to tell the listview update the data I have got for php. I have try to use notifyDataSetChanged();, but I do know where should it put.
public class List_View extends ListFragment{
private String result;
private ListView listView;
private ArrayList<String> items = new ArrayList<String>();
final String uri = "http://localhost/userinfo.php";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.list, container, false);
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items));
return rootView;
}
class sendPostRunnable implements Runnable{
#Override
public void run(){
result = sendPostDataToInternet();
String temp = "Not result.";
try {
JSONTokener jsonTokener = new JSONTokener(result);
JSONObject jsonObject = (JSONObject) jsonTokener.nextValue();
JSONArray jarray = jsonObject.getJSONArray("response");
for (int i = 0; i < jarray.length(); i++) {
temp = "";
JSONObject jobject = jarray.getJSONObject(i);
temp += "name: "+jobject.getString("name")+"\n";
temp += "email: "+jobject.getString("email");
items.add(temp);
temp = "";
}
if(jarray.length() < 1){
items.add(temp);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private String sendPostDataToInternet(){
HttpPost httpRequest = new HttpPost(uri);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("uid", "u1"));
try{
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
if (httpResponse.getStatusLine().getStatusCode() == 200){
String strResult = EntityUtils.toString(httpResponse.getEntity());
return strResult;
}
} catch (Exception e){
e.printStackTrace();
}
return null;
}
}
You should collect all arrived data in other collection (other than used in list adapter) in separate thread and then replace the list colletion source and right after than you should call notifyDataSetChanged().
public class List_View extends ListFragment{
private String result;
private ListView listView;
protected List newData;
protected ArrayAdapter listAdapter;
private ArrayList<String> items = new ArrayList<String>();
final String uri = "http://localhost/userinfo.php";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.list, container, false);
listAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
setListAdapter(listAdapter );
return rootView;
}
class sendPostRunnable implements Runnable{
#Override
public void run(){
result = sendPostDataToInternet();
String temp = "Not result.";
// a new collection to fill from response
newData = new ArrayList<String>();
try {
JSONTokener jsonTokener = new JSONTokener(result);
JSONObject jsonObject = (JSONObject) jsonTokener.nextValue();
JSONArray jarray = jsonObject.getJSONArray("response");
for (int i = 0; i < jarray.length(); i++) {
temp = "";
JSONObject jobject = jarray.getJSONObject(i);
temp += "name: "+jobject.getString("name")+"\n";
temp += "email: "+jobject.getString("email");
//here you should create a corresponding object from JSON
// and add it to newData List
newData .add(temp);
temp = "";
}
if(jarray.length() < 1){
items.add(temp);
}
// here you will have a newData List filled so you should
// replace or add data from this List to ListView's used
items.add(newData);
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private String sendPostDataToInternet(){
HttpPost httpRequest = new HttpPost(uri);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("uid", "u1"));
try{
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
if (httpResponse.getStatusLine().getStatusCode() == 200){
String strResult = EntityUtils.toString(httpResponse.getEntity());
return strResult;
}
} catch (Exception e){
e.printStackTrace();
}
return null;
}
}

Categories

Resources