Dynamically Generate and show Table in Android Studio - java

I'm creating my first app on android, accordingly I have low experience to develop android apps and I'm fist time use java too.
What I want ?
I want to generate table from ArrayList
What's the problem ?
I have problem when I generate table. When "for" loop finished debugger stands in catch block (but when I mouse over "e", it writes - "local variable e is not defined" and I can not read some error) after that I see on phone screen -"unfortunately app is closed"
What's happen without For Loop ?
Without For loop everything works well, when I try to show only one object.
Please help and give me suggestions, Thanx.
Hare is Java code:
try {
ArrayList<Persons> otherPersons = new ArrayList<Persons>();
otherPerosons = GetPersonsList();//from service
// /* Find Tablelayout defined in main.xml */
TableLayout tl = (TableLayout) findViewById(R.id.dynamictable);
TextView[] title = new TextView[1000];
TableRow[] tr = new TableRow[1000];
LinearLayout.LayoutParams trparams;
LinearLayout.LayoutParams titleparams;
for (int y=0; y < otherPersons.size(); y++) {
/* Create a new row to be added. */
tr[y] = new TableRow(this);
tr[y].setId(y+100);
tr[y].setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT));
trparams = (LinearLayout.LayoutParams) tr[y].getLayoutParams();
trparams.setMargins(0, 8, 0, 5); //substitute parameters for left, top, right, bottom
tr[y].setLayoutParams(trparams);
/* Create a TextView to be the row-content. */
title[y] = new TextView(this);
title[y].setText(otherPersons.get(y).Name);
title[y].setId(y +200);
title[y].setTextColor(Color.parseColor("#000000"));
title[y].setGravity(Gravity.LEFT);
title[y].setLayoutParams(new TableLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 34));
titleparams = (LinearLayout.LayoutParams) title[y].getLayoutParams();
titleparams.setMargins(5, 0, 0, 0); //substitute parameters for left, top, right, bottom
title[y].setLayoutParams(titleparams);
tr[y].addView(title[y]);
/* Add row to TableLayout. */
tl.addView(tr[y], new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
}
} catch (Exception e) {
e.printStackTrace();
}
Hare is my Design XML:
<TableLayout
android:id="#+id/dynamictable"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:shrinkColumns="*"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="39dp"
android:stretchColumns="*"
android:background="#ffB224">
</TableLayout>

I don't know the answer, but try to put your exception-output in your logcat output with
try{
}catch(Exception e){
Log.e("ClassName", e.toString());
}
Maybe you see more information about the exception.
Here you can find more information about Android Logging

Related

Creating dynamic buttons in android

I am working on Watson Conversation chatbot. I have been trying to implement the 'options' response type in my chatbot application. My problem is "Creating 'n' number of dynamic buttons in Android where n is the number of label names of options present in the backend(IBM Watson Conversation)"
I have been able to retrieve the label names in form of text. Now I have to put these label names in "clickable buttons". Such that when a user clicks on a button, a value is passed to the backend (Watson Conversation API).
This is how I am retrieving option(response type) from backend. Watson Conversation sends reply in form of JSON.
Label name retrieving code:
str = response.getOutput().getGeneric().get(i).getResponseType();
JSONArray arrayOptions = new JSONArray(response.getOutput().getGeneric().get(i).getOptions());
int j=0; //j is used to count the number of options
while (j<arrayOptions.length()){
final Message outMessage2 = new Message();
outMessage2.setMessage(response.getOutput().getGeneric().get(i).getOptions().get(j).getLabel());
outMessage2.setId("2");
System.out.println(outMessage2);
messageArrayList.add(outMessage2);
j++;
}
Try this to solve your problem
First create a LinearLayout Layout inside xml
<LinearLayout
android:id="#+id/layout_dynamic"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:orientation="vertical">
</LinearLayout>
After that, use below code
LinearLayout layout_dynamic =(LinearLayout) findViewById(R.id.layout_dynamic);
for (int i = 0; i < YOURARRAY.length(); i++) {
String label = <Button Name as You Like>;
LinearLayout childLayout = new LinearLayout(getActivity());
LinearLayout.LayoutParams linearParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT LinearLayout.LayoutParams.WRAP_CONTENT);
childLayout.setLayoutParams(linearParams);
Button btnName = new Button(getActivity());
btnName.setLayoutParams(newTableLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT, 1f));
childLayout.addView(btnName, 0);
layout_dynamic.addView(childLayout);}
Hope this will help you.

Android MPChart: drawing lines of different plots on the same activity in different colors

I'm using the MPAndroidChart library to create several plots and update them in realtime with different sources of data. I want each plot to have a line of a different color. The problem is that all plots show up with a line of the same color even if I specify another color for a different plot. Moreover I need to update each chart with different sources of data but I suspect all of them are using just one source of data which suggests to me that the same problem with the color is happening with the data.
This is part of how I specify the different plots inside my activity file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:id="#+id/linearLayout">
<com.github.mikephil.charting.charts.LineChart
android:id="#+id/chart1"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/linearLayout"
android:id="#+id/linearLayout2">
<com.github.mikephil.charting.charts.LineChart
android:id="#+id/chart2"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
...
I have 8 of these plots stacked together and they show correctly on my app one after the other. Then on my activity file I initialize each one of them like this
OnChartValueSelectedListener ol = new OnChartValueSelectedListener(){
#Override
public void onValueSelected(Entry entry, Highlight h) {
//entry.getData() returns null here
}
#Override
public void onNothingSelected() {
}
};
mChart1 = (LineChart) findViewById(R.id.chart1);
mChart1.setOnChartValueSelectedListener(ol);
mChart2 = (LineChart) findViewById(R.id.chart2);
mChart2.setOnChartValueSelectedListener(ol);
...
Then when I'm receiving the data I do
LineData data1 = mChart1.getData();
if (data1 != null) {
ILineDataSet set1 = data1.getDataSetByIndex(0);
// set.addEntry(...); // can be called as well
if (set1 == null) {
set1 = createSet();
data1.addDataSet(set1);
}
data1.addEntry(new Entry(set1.getEntryCount(), f), 0);
data1.notifyDataChanged();
// let the chart know it's data has changed
mChart1.notifyDataSetChanged();
// limit the number of visible entries
mChart1.setVisibleXRangeMaximum(20);
// move to the latest entry
mChart1.moveViewToX(data1.getEntryCount());
}
LineData data2 = mChart2.getData();
if (data2 != null) {
ILineDataSet set2 = data2.getDataSetByIndex(0);
// set.addEntry(...); // can be called as well
if (set2 == null) {
set2 = createSet2();
data2.addDataSet(set2);
}
data2.addEntry(new Entry(set2.getEntryCount(), f), 0);
data2.notifyDataChanged();
// let the chart know it's data has changed
mChart2.notifyDataSetChanged();
// limit the number of visible entries
mChart2.setVisibleXRangeMaximum(20);
// move to the latest entry
mChart2.moveViewToX(data2.getEntryCount());
}
And then I have the createSet functions which assign a different color
private LineDataSet createSet() {
LineDataSet set1 = new LineDataSet(null, "");
set1.setAxisDependency(YAxis.AxisDependency.LEFT);
set1.setColor(ColorTemplate.getHoloBlue());
set1.setCircleColor(Color.WHITE);
set1.setLineWidth(1f);
set1.setCircleRadius(1f);
set1.setFillAlpha(65);
set1.setFillColor(ColorTemplate.getHoloBlue());
set1.setHighLightColor(Color.rgb(244, 117, 117));
set1.setValueTextColor(Color.WHITE);
set1.setValueTextSize(0.1f);
set1.setDrawValues(false);
return set1;
}
private LineDataSet createSet2() {
LineDataSet set2 = new LineDataSet(null, "");
set2.setAxisDependency(YAxis.AxisDependency.LEFT);
set2.setColor(Color.GREEN);
set2.setCircleColor(Color.WHITE);
set2.setLineWidth(1f);
set2.setCircleRadius(1f);
set2.setFillAlpha(65);
set2.setHighLightColor(Color.rgb(44, 117, 117));
set2.setValueTextColor(Color.WHITE);
set2.setValueTextSize(0.1f);
set2.setDrawValues(false);
return set2;
}
Where you see the set color is one set to getHoloBlue() which is a default test color and the other is set to Color.GREEN. The problem is all 8 of the plots have the getHoloBlue color. If I put another color on the first createSet function they all change to that color.
I'm new to Android development so I'm sure I'm missing something here.
Instead of this:
ILineDataSet set1 = data1.getDataSetByIndex(0);
ILineDataSet set2 = data2.getDataSetByIndex(0);
Create separate datasets for every chartview as:
LineDataSet lineDataSet1 = new LineDataSet(lineEntries1, "legend");
LineDataSet lineDataSet2 = new LineDataSet(lineEntries2, "legend");
// line entries are arraylist of strings
enter code here
After that:
LineData lineData1 = new LineData(lineDataSet1);
LineData lineData2 = new LineData(lineDataSet2);
Then:
mChart1.setData(lineData1);
mChart2.setData(lineData2);
Follow that flow I think there is issue you are making array of dataset which is not required moreover I think you are doing something wrong in defining datasets and data. In normal flow we provide dataset to data but in your solution its opposite.
For normal flow of single line in single chart view follow example below and add different chartviews and datasets in that way.
Example:
ArrayList<Entry> lineEntries = new ArrayList<Entry>();
lineEntries.add(new Entry(0, 1));
lineEntries.add(new Entry(1, 2));
lineEntries.add(new Entry(2, 3));
lineEntries.add(new Entry(3, 4));
lineEntries.add(new Entry(4, 2));
lineEntries.add(new Entry(5, 3));
lineEntries.add(new Entry(6, 1));
lineEntries.add(new Entry(7, 5));
lineEntries.add(new Entry(8, 7));
lineEntries.add(new Entry(9, 6));
lineEntries.add(new Entry(10, 4));
lineEntries.add(new Entry(11, 5));
LineDataSet lineDataSet = new LineDataSet(lineEntries, "Oil Price");
lineDataSet.setAxisDependency(YAxis.AxisDependency.LEFT);
lineDataSet.setHighlightEnabled(true);
lineDataSet.setLineWidth(2);
lineDataSet.setColor(getColor("defaultBlue"));
lineDataSet.setCircleColor(getColor("defaultOrange"));
lineDataSet.setCircleRadius(6);
lineDataSet.setCircleHoleRadius(3);
lineDataSet.setDrawHighlightIndicators(true);
lineDataSet.setHighLightColor(Color.RED);
lineDataSet.setValueTextSize(12);
lineDataSet.setValueTextColor(getColor("primaryDark"));
LineData lineData = new LineData(lineDataSet);
lineChart.getDescription().setText("Price in last 12 days");
lineChart.getDescription().setTextSize(12);
lineChart.setDrawMarkers(true);
lineChart.setMarker(markerView(context));
lineChart.getAxisLeft().addLimitLine(lowerLimitLine(2,"Lower Limit",2,12,getColor("defaultOrange"),getColor("defaultOrange")));
lineChart.getAxisLeft().addLimitLine(upperLimitLine(5,"Upper Limit",2,12,getColor("defaultGreen"),getColor("defaultGreen")));
lineChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTH_SIDED);
lineChart.animateY(1000);
lineChart.getXAxis().setGranularityEnabled(true);
lineChart.getXAxis().setGranularity(1.0f);
lineChart.getXAxis().setLabelCount(lineDataSet.getEntryCount());
lineChart.setData(lineData);

Android - TableRow column alignment programmatically

I have been stuck on this issue for hours and I have no idea how to get passed it.
I have programatically created a table (no problem), but this is the issue I am having. When I create the row, I would then like to create two separate columns. As you'll see in my example, I have two different TextViews on the same line ('Type' and 'Number'). As it stands, both of them are shifted over to the left.
What I would like is for them to be in two separate columns, equally split apart centred in each column.
Here is the relevant code to what I am trying to accomplish.
TableLayout serviceLineLayout = new TableLayout(getContext());
serviceLineLayout.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.MATCH_PARENT));
TableRow firstTableRow = getFirstTableRow(getContext());
serviceLineLayout.addView(firstTableRow);
private TableRow getFirstTableRow(Context context) {
TableRow tableRow = new TableRow(context);
tableRow.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT));
TextView typeHeader = new TextView(context);
typeHeader.setId(0);
typeHeader.setText("Type");
typeHeader.setTextSize(20);
tableRow.addView(typeHeader);
TextView numberHeader = new TextView(context);
numberHeader.setId(0);
numberHeader.setText("Number");
numberHeader.setTextSize(20);
numberHeader.setGravity(Gravity.RIGHT);
tableRow.addView(numberHeader);
return tableRow;
}
For this tablelayout defined in xml, following will be the dynamic code in corresponding java file (Activity/Fragment).
<TableLayout
android:id="#+id/fenceTableLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</TableLayout>
Activity logic for TableView
//Table Layout parameters
TableRow.LayoutParams textViewParam = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT,1.0f);
TableLayout tableLayout = (TableLayout) view.findViewById(R.id.fenceTableLayout);
TableRow trHead = new TableRow(context);
LayoutParams tableRowParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
trHead.setLayoutParams(tableRowParams);
TextView nameHead = new TextView(context);
nameHead.setText("Content left");
nameHead.setLayoutParams(textViewParam);
nameHead.setGravity(Gravity.CENTER);
trHead.addView(nameHead);
TextView detailHead = new TextView(context);
detailHead.setText("Content right");
detailHead.setGravity(Gravity.CENTER);
detailHead.setLayoutParams(textViewParam);
trHead.addView(detailHead);
tableLayout.addView(trHead);
NOTE:
Many values have been referred from resource files, You can either neglect/replicate those.

how to align text to top of a text view dynamically

I have hit a problem when trying to align my text to the top of a text view dynamically. I have a method that creates textviews dynamically. I have set the gravity of the text view to Gravity.TOP. Which a believe should place the text at the very top of the textView object. However when I run the project there is a gap of about 2 lines of text from the top of the object. I can work around this by changing the height of the textView but I would rather it loaded in an set the size depending on how much text there is too load into the textView.
Here is my function, it works well and does what it is supposed to do:
public void addItems(LinearLayout page,int id,String text,int row){
LinearLayout item = new LinearLayout(this);
item.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
TextView itemNum = new TextView(this);
//itemNum.setLayoutParams(new ViewGroup.LayoutParams(50,50));
itemNum.setWidth(50);
itemNum.setTextSize(40);
itemNum.setTextAppearance(getApplicationContext(), R.style.large_text);
itemNum.setLeft(0);
itemNum.setText(row+":");
LayoutParams numParams = new LinearLayout.LayoutParams(70, 70);
numParams.setMargins(25, 0, 0, 0);
TextView itemDetails = new TextView(this);
itemDetails.setLayoutParams(new ViewGroup.LayoutParams(150,LayoutParams.WRAP_CONTENT));
itemDetails.setText(text);
itemDetails.setWidth(100);
itemDetails.setLeft(5);
itemDetails.setRight(5);
itemDetails.setTop(0);
itemDetails.setVisibility(View.VISIBLE);
itemDetails.setGravity(itemDetails.getGravity() | Gravity.TOP);
itemDetails.setPadding(0,0,0,0);
Button delete = new Button(this);
//delete.setLayoutParams(new ViewGroup.LayoutParams(50,50));
delete.setText("Delete");
LayoutParams btnParams = new LinearLayout.LayoutParams(70, 70);
btnParams.setMargins(0, 0, 15, 0);
item.addView(itemNum,numParams);
item.addView(itemDetails);
item.addView(delete,btnParams);
page.addView(item);
Log.d("Loop","Loop is adding function in");
}
If anybody can see where I have gone wrong I would really appreciate it. The method above may seem very long winded but I am new to Java.
Not sure if it will help but here is my string to show in the textView:
String formatText = lat + ", " + lng + " /n" + result;

getLocationOnScreen crashes

I need to get the coordinates of my app on screen to use them as an offset for a popout.
View tempView = (View) findViewById(R.layout.main);
int[] loc = {0,0};
tempView.getLocationOnScreen(loc); /// crashes here!
Tried this code, but the last line of it makes the app crash. Maybe the tempView I'm getting from the main layout somehow doesn't correspond with the layout on screen?
Any suggestions... thanks! :)
added:
solved
int[] loc = new int[2];
View tempView = (View) findViewById(R.id.LL_whole);
tempView.getLocationOnScreen(loc);
post( String.valueOf(loc[1]) );
works! :)
Try checking to see if tempView is null. I suspect findViewById() is failing to find the id you've given it.
int[] loc = {0,0};
View tempView = (View) findViewById(R.layout.main);
if (tempView != null) {
tempView.getLocationOnScreen(loc);
} else {
Log.d("YourComponent", "tempView was null.");
}
In your XML you have something like this:
<SomeLayout android:id="#+id/myLayout" ... >
<SomeView android:id="#+id/myView" ... />
<SomeOtherView android:id="#+id/myOtherView" .../>
</SomeLayout>
So you want to say:
SomeView v = (SomeView)findViewById(R.id.myView);
Or perhaps:
SomeLayout l = (SomeLayout)findViewById(R.id.myLayout);
findViewById(R.layout.main)
You should place here R.id.something not R.layout.something.

Categories