This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
here is my code: Manifest file of my calculator project.:
When i try to launch the application on my phone which runs android 4.4.2 kitkat version , it says that calculator stopped forced close.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.jeet.calculator"
android:versionCode="1"
android:versionName="1.0">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Here is my xml code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight= "30">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/textview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_gravity="right"
android:gravity="right"
android:padding="10dp"
android:text=""/>
<TextView
android:id="#+id/textview2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_gravity="right"
android:gravity="right"
android:padding="10dp"
android:text=""
android:layout_marginBottom="10dp" />
<Button
android:id="#+id/clear"
style="?android:attr/buttonStyleSmall"
android:layout_width="260dp"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Clear"
android:layout_marginLeft="60dp" />
<LinearLayout
android:layout_width="fill_parent"
android:gravity="center"
android:layout_marginTop="10dp"
android:orientation="horizontal"
android:layout_height="wrap_content">
<Button
android:id="#+id/one"
android:layout_width="65dp"
android:layout_height="55dp"
android:text="1" />
<Button
android:id="#+id/two"
android:layout_width="65dp"
android:layout_height="55dp"
android:text="2"/>
<Button
android:id="#+id/three"
android:layout_width="65dp"
android:layout_height="55dp"
android:text="3"/>
<Button
android:id="#+id/add"
android:layout_width="65dp"
android:layout_height="55dp"
android:text="+"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<Button
android:id="#+id/four"
android:layout_width="65dp"
android:layout_height="55dp"
android:text="4"/>
<Button
android:id="#+id/five"
android:layout_width="65dp"
android:layout_height="55dp"
android:text="5"/>
<Button
android:id="#+id/six"
android:layout_width="65dp"
android:layout_height="55dp"
android:text="6"/>
<Button
android:id="#+id/minus"
android:layout_width="65dp"
android:layout_height="55dp"
android:text="-"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<Button
android:id="#+id/seven"
android:layout_width="65dp"
android:layout_height="55dp"
android:text="7"/>
<Button
android:id="#+id/eight"
android:layout_width="65dp"
android:layout_height="55dp"
android:text="8"/>
<Button
android:id="#+id/nine"
android:layout_width="65dp"
android:layout_height="55dp"
android:text="9"/>
<Button
android:id="#+id/divide"
android:layout_width="65dp"
android:layout_height="55dp"
android:text="/"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<Button
android:id="#+id/ce"
android:layout_width="65dp"
android:layout_height="55dp"
android:text="CE"/>
<Button
android:id="#+id/zero"
android:layout_width="65dp"
android:layout_height="55dp"
android:text="0"/>
<Button
android:id="#+id/equal"
android:layout_width="65dp"
android:layout_height="55dp"
android:text="="/>
<Button
android:id="#+id/mul"
android:layout_width="65dp"
android:layout_height="55dp"
android:text="*"/>
</LinearLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
Here is the MainActivity code in Java:
package com.example.jeet.calculator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button b1, b2, b3, b4, b5, b6, b7, b8, b9, bzero, bAdd, bSub, bMul, bDiv, bClear, bEqual,bCe;
TextView txt1, txt2;
String s = "", s1 = "" , s2 = "" , resultString = "";
int i =0 , i1 = 0, c = -1;
int result = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.real);
b1 = (Button)findViewById(R.id.one);
b2 = (Button) findViewById(R.id.two);
b3 = (Button)findViewById(R.id.three);
b4 = (Button)findViewById(R.id.four);
b5 = (Button)findViewById(R.id.five);
b6 = (Button)findViewById(R.id.six);
b7 = (Button)findViewById(R.id.seven);
b8 = (Button)findViewById(R.id.eight);
b9 = (Button)findViewById(R.id.nine);
bzero = (Button)findViewById(R.id.zero);
bAdd = (Button)findViewById(R.id.add);
bSub = (Button)findViewById(R.id.minus);
bMul = (Button)findViewById(R.id.mul);
bDiv = (Button)findViewById(R.id.divide);
bClear = (Button)findViewById(R.id.clear);
bCe = (Button)findViewById(R.id.ce);
txt1 = (TextView)findViewById(R.id.textview1);
txt2 = (TextView)findViewById(R.id.textview2);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
s = (String) txt1.getText();
if (s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")) {
txt1.setText("");
s = "";
}
txt1.setText(s + "1");
s = "";
}
});
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
s = (String) txt1.getText();
if (s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")) {
txt1.setText("");
s = "";
}
txt1.setText(s + "2");
s = "";
}
});
b3.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
s = (String)txt1.getText();
if(s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")) {
txt1.setText("");
s = "";
}
txt1.setText(s + "3");
s = "";
}
});
b4.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
s = (String)txt1.getText();
if(s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")){
txt1.setText("");
s = "";
}
txt1.setText(s + "4");
s = "";
}
});
b5.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
s = (String)txt1.getText();
if(s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")){
txt1.setText("");
s = "";
}
txt1.setText(s + "5");
s = "";
}
});
b6.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
s = (String)txt1.getText();
if(s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")){
txt1.setText("");
s = "";
}
txt1.setText(s + "6");
s = "";
}
});
b7.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
s = (String)txt1.getText();
if(s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")){
txt1.setText("");
s = "";
}
txt1.setText(s + "7");
s = "";
}
});
b8.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
s = (String)txt1.getText();
if(s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")){
txt1.setText("");
s = "";
}
txt1.setText(s + "8");
s = "";
}
});
b9.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
s = (String)txt1.getText();
if(s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")){
txt1.setText("");
s = "";
}
txt1.setText(s + "9");
s = "";
}
});
bzero.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
s = (String)txt1.getText();
if(s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")){
txt1.setText("");
s = "";
}
txt1.setText(s + "0");
s = "";
}
});
bCe.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
txt1.setText("");
txt2.setText("");
i = 0;
i1 = 0;
s1 = "";
s2 = "";
resultString = "";
c = -1;
result = 0;
}
});
bClear.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
s = (String)txt1.getText();
if(s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/") || s.equals("")){
i = 0;
}
else{
i = Integer.parseInt(s);
i = i/10;
}
if(i == 0){
txt1.setText("");
}
else{
txt1.setText(i + "");
}
s = null;
}
});
bAdd.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
String tmp = (String)txt1.getText();
if(tmp.isEmpty()){
s1 = "0";
}
else if(!tmp.equals("+") && !tmp.equals("-") && !tmp.equals("*") && !tmp.equals("/")){
s1 = tmp;
}
c = 0;
resultString = "";
txt1.setText("+");
txt2.setText(s1 + " + ");
}
});
bSub.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
String tmp = (String)txt1.getText();
if(tmp.isEmpty()){
s1 = "0";
}
else if(!tmp.equals("+") && !tmp.equals("-") && !tmp.equals("*") && !tmp.equals("/")){
s1 = tmp;
}
c= 1;
resultString = "";
txt1.setText("-");
txt2.setText(s1 + " - ");
}
});
bMul.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
String tmp = (String)txt1.getText();
if(tmp.isEmpty()){
s1 = "0";
}
else if(!tmp.equals("+") && !tmp.equals("-") && !tmp.equals("*") && !tmp.equals("/")){
s1 = tmp;
}
c= 3;
resultString = "";
txt1.setText("*");
txt2.setText(s1 + " * ");
}
});
bDiv.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
String tmp = (String)txt1.getText();
if(tmp.isEmpty()){
s1 = "0";
}
else if(!tmp.equals("+") && !tmp.equals("-") && !tmp.equals("*") && !tmp.equals("/")){
s1 = tmp;
}
c= 2;
resultString = "";
txt1.setText("/");
txt2.setText(s1 + " / ");
}
});
bEqual.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String operator = "";
if (s1.equalsIgnoreCase("+") || s1.equalsIgnoreCase("-") || s1.equalsIgnoreCase("/") || s1.equalsIgnoreCase("*")) {
i = 0;
} else if (s1 == null || s1.isEmpty()) {
i = 0;
} else {
i = Integer.parseInt(s1);
}
if(resultString.isEmpty()) {
s2 = (String) txt1.getText();
if (s2.equalsIgnoreCase("+") || s2.equalsIgnoreCase("-") || s2.equalsIgnoreCase("/") || s2.equalsIgnoreCase("*")) {
i1 = 0;
} else if (s2 == null || s2.isEmpty()) {
i1 = 0;
} else {
i1 = Integer.parseInt(s2);
}
} else {
i = result;
}
if (c == 0) {
operator = "+";
result = i + i1;
} else if (c == 1) {
operator = "-";
result = i - i1;
} else if (c == 2) {
operator = "/";
if (i1 == 0) {
Toast.makeText(getApplicationContext(),
"Invalid Input", Toast.LENGTH_LONG).show();
result = 0;
} else {
result = i / i1;
}
} else if (c == 3) {
operator = "*";
result = i * i1;
} else {
operator = "";
result = 0;
}
//History Storage
if(!operator.isEmpty()) {
txt2.setText(i + " " + operator + " " + i1);
} else {
txt2.setText("");
}
resultString = String.valueOf(result);
txt1.setText(resultString);
}
});
}
}
The Logcat error is as follows:
**02-09 23:39:17.070 766-766/com.example.jeet.calculator E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.jeet.calculator, PID: 766
java.lang.RuntimeException: Unable to start activity** ComponentInfo{com.example.jeet.calculator/com.example.jeet.calculator.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2338)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5299)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.jeet.calculator.MainActivity.onCreate(MainActivity.java:347)
at android.app.Activity.performCreate(Activity.java:5264)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2302)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5299)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
at dalvik.system.NativeStart.main(Native Method)
I'm not sure but i think you forgot to do FindViewById on bEqual
Related
I have added this code to my MainActivity.java:
tv6.setText("11111111111\n"+strPokus2+"\nA\n"+strPokus+"\nB");
tv6.setSingleLine(true);
tv6.setMarqueeRepeatLimit(-1);
tv6.setEllipsize(TextUtils.TruncateAt.MARQUEE);
tv6.setSelected(true);
HOWEVER, the text is still static, not rotating/moving. What's wrong ??
HERE IS MainActivity.java and activity_main.xml below it:
package com.example.tablelayout6;
import androidx.appcompat.app.AppCompatActivity;
import android.icu.text.MeasureFormat;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TableRow;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.TableLayout;
import android.text.TextUtils;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import java.lang.StringBuilder;
public class MainActivity extends AppCompatActivity {
public boolean g=true;
public Integer N=1;
public String a="2";
private EditText editText1;
private EditText linear;
private Integer[] hodnoty =new Integer[10];
private String[] koal=new String[10];
private float[] shap=new float[10];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public boolean iswinning(Integer J,int ii) {
return true;
}
public Integer fact (Integer f) {
if (f==0) return 1;
else return f*fact((Integer) (f-1));
}
//T pocetHracu
public Integer[] stringToArray(String binary) {
Integer[] arrayOfPLayers=new Integer[binary.length()];
for(int i=0;i<binary.length();i++) {
arrayOfPLayers[i]=Integer.parseInt("" + binary.charAt(i));
}
return arrayOfPLayers;
}
//N je pocet koalici
public void click5(View view) {
int pocetHracu=Integer.toBinaryString(N-1).length();
Integer[][] koalice=new Integer[N][pocetHracu];
Integer[][] koalice2=new Integer[N][pocetHracu];
Integer[][] koalice3=new Integer[N][pocetHracu];
TextView tv6 = (TextView) findViewById(R.id.textView6);
for (Integer ith=0;ith<N;ith++) {
for(Integer T=0;T<pocetHracu;T++) {
String StringPadded=stf(Integer.toBinaryString(ith),pocetHracu-Integer.toBinaryString(ith).length());
koalice[ith][T]=stringToArray(StringPadded)[T];
koalice2[ith][T]=stringToArray(StringPadded)[T];
koalice3[ith][T]=stringToArray(StringPadded)[T];
}
}
float[] shap=new float[pocetHracu];
float[] vyhryKoalici = new float[N];
Integer[] isSwing=new Integer[pocetHracu];
for (int i=0; i<N;i++) {
editText1 = (EditText) findViewById(330+i);
String a=editText1.getText().toString();
float f1 = Float.parseFloat(a);
vyhryKoalici[i]=f1;
}
Integer[] kolikJeSwingu= new Integer[pocetHracu];
String S="";
String kde="j";
Integer jth;
for (int p = 0; p < pocetHracu; p++) {
isSwing[p] =0;
kolikJeSwingu[p]=N;
}
// Integer swingove2=pocetHracu*N;
Integer bool=1;
Integer canBanzhaf=1;
for(Integer contr=0;contr<N;contr++)
{
if(vyhryKoalici[contr]!=0 && vyhryKoalici[contr]!=1) {
canBanzhaf=0;
}
}
for(Integer T=0;T<pocetHracu;T++) {
for (Integer ith = 0; ith < N; ith++) {
bool = 1;
//vyhryKoalici[ith];
//musis najit jth<N pro ktere koalice3[jth]=S-ith
if ((koalice[ith][T] == 1) && (vyhryKoalici[ith]==1)) {
koalice3[ith][T] = 0;
for (jth = 0; jth < N; jth++) {
for (Integer k = 0; k < pocetHracu; k++)
{
//if (k != T && koalice[ith][k] != koalice3[jth][k]) {
if ((k != T) && (koalice[ith][k] != koalice3[jth][k])) {
bool = 0;
// swingove2--;
kde+="\nk"+k.toString()+"T"+T.toString()+">";
}
}
kde+="\njth"+jth.toString()+"ith"+ith.toString()+"T"+T.toString();
//(vyhryKoalici[jth]
if ((vyhryKoalici[jth]==0) && (bool == 1)) {
isSwing[T]++;
}
bool=1;
}
koalice3[ith][T]=1;
bool=1;
}
}
}
//kolikJeSwingu(Integer TmaSwing, Integer pocetHracu, Integer pocetKoalici,
// Integer[][] koal, Integer[] koalicePriKtereJeSwing, float[] vyhryKoal)
for (Integer ith = 0; ith < N; ith++) {
for(Integer T=0;T<pocetHracu;T++) {
//isSwingBool(Integer kteraKoalice, Integer TmaSwing, Integer pocetHracu, Integer pocetKoalici,
// Integer[][] koal, Integer[] koalicePriKtereJeSwing, float[] vyhryKoal) {
// kolikJeSwingu[T]+=kolikJeSwingu(T, pocetHracu, N,
// koalice, koalice[ith],vyhryKoalici);
if (koalice[ith][T] == 1) {
koalice2[ith][T] = 0;
for (jth = 0; jth < N; jth++) {
bool = 1;
for (int k = 0; k < pocetHracu; k++) {
if (k != T && koalice[ith][k] != koalice2[jth][k]) {
bool = 0;
}
}
int bool2=0;
koalice2[ith][T] = 1;
if (vyhryKoalici[ith] == 1 && vyhryKoalici[jth] == 0) {
for (int k = 0; k < pocetHracu; k++) {
if (koalice[ith][k] != koalice2[jth][k]) {
bool2++;
}
}
// if(bool2==1) {
// isSwing[T]++;
// }
}
koalice2[ith][T] = 1;
Integer t = 0;
for (int p = 0; p < pocetHracu; p++) {
t += koalice[ith][p];
}
// Integer[] isSwing=new Integer[pocetHracu];
if (bool == 1) {
shap[T] += (float) ((float) fact(t - 1) * fact(pocetHracu - t) / (float) (fact(pocetHracu)) * (float) (vyhryKoalici[ith] - vyhryKoalici[jth]));
}
}
}
}
}
S+="here";
String T2="";
T2+="banzhaf";
Integer swingove=0;
for(int p=0;p<pocetHracu;p++) {
swingove+=isSwing[p];
}
String strPokus="";
if(canBanzhaf==1) {
strPokus = "banzhaf ";
} else {
strPokus="banzhaf err ";
}
float[] banzh=new float[pocetHracu];
for(int p=0;p<pocetHracu;p++)
{
banzh[p]=(float) isSwing[p]/(float) swingove;
}
String strPokus2="shap ";
for(int i=0;i<pocetHracu;i++) {
// S+=(" "+String.valueOf(shap[i]));
strPokus2+=String.format("%.2f ",shap[i]);
strPokus+=String.format("%.2f ",banzh[i]);
}
// tv6.setText(strPokus2+"\n"+strPokus+"\nswing"+isSwing[0]+"swingPrvni:"+isSwing[1]+"\nH"+swingove);
tv6.setText("11111111111\n"+strPokus2+"\nA\n"+strPokus+"\nB");
tv6.setSingleLine(true);
tv6.setMarqueeRepeatLimit(-1);
tv6.setEllipsize(TextUtils.TruncateAt.MARQUEE);
tv6.setSelected(true);
// TextView textView=(TextView)findViewById(R.id.text_test);
/* tv6.setEllipsize(TextUtils.TruncateAt.MARQUEE);
tv6.setSingleLine(true);
tv6.setMarqueeRepeatLimit(-1);
tv6.setFocusableInTouchMode(true);
tv6.setFocusable(true);
*/
/* TextView txt = new TextView(this);
txt.setText("This is the infinite marquee");
txt.setEllipsize(TextUtils.TruncateAt.MARQUEE);
txt.setSingleLine(true);
txt.setMarqueeRepeatLimit(-1);
txt.setSelected(true);
*/
}
public void click4(View view) {
//
if (g) {
linear = (EditText) findViewById(R.id.simpleEditText);
if (N == 1) {
linear.setText("1");
}
String a = linear.getText().toString();
N = Integer.parseInt(a);
N++;
linear.setText(N.toString());
}
}
public void click7(View view) {
if (g) {
//
linear = (EditText) findViewById(R.id.simpleEditText);
if (N == 0 || N == 1) {
linear.setText("1");
}
String a = linear.getText().toString();
N = Integer.parseInt(a);
if (N > 1) N--;
linear.setText(N.toString());
}
}
public String stf(String a,Integer l) {
if(l==0) { return a; }
l--;
return stf("0"+a,l);
}
public void click2(View view) {
if (g) {
g = false;
String col1;
String col2;
// String playerChanged;
TableLayout tl = (TableLayout) findViewById(R.id.tableLayout1);
EditText editText = (EditText) findViewById(R.id.simpleEditText);
TableRow row = new TableRow(this);
TextView tv = new TextView(this);
TextView c = new TextView(this);
//EditText etUserInfoNewValue = (EditText)findViewById(R.id.simpleEditText);
// a = editText.getText().toString();
tv.setId(202);
tv.setText("This is text");
//
tl.addView(row);
row.addView(tv);
int sf = Integer.toBinaryString(N - 1).length();
for (int x = 0; x < N; x++) {
//String.format("%010d",(
String jl = Integer.toBinaryString(x);
String jl2 = stf(jl, sf - jl.length());
//koal[x]=jl2;
col1 = "(" + x + ")" + jl2;
// col1 = "(" + x + ")"+Integer.toBinaryString(x);
col2 = "1";
//col3 = "(" + x + ") Column 3";
//col4 = "(" + x + ") Column 4";
TableRow newRow = new TableRow(this);
TextView column1 = new TextView(this);
TextView column2 = new TextView(this);
EditText editText1 = new EditText(this);
editText1.setId(330 + x);
// String stringAnswer = editText1.getText().toString();
TextView column3 = new TextView(this);
// TextView column4 = new TextView(this);
editText1.setText("0 ");
column1.setText(col1);
column1.setText(col1);
column2.setText(col2);
//column3.setText(col3);
//column4.setText(col4);
// column1.setText(stringAnswer);
newRow.addView(column1);
newRow.addView(editText1);
newRow.addView(column3);
// newRow.addView(column4);
tl.addView(newRow, new TableLayout.LayoutParams());
}
}
}
}
XML XML XML XML:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="bottom|fill_horizontal"
android:layout_span="#integer/material_motion_duration_long_2"
android:background="#FFFFFF"
android:backgroundTint="#FFFFFF"
android:backgroundTintMode="multiply"
android:foregroundGravity="fill_horizontal|center_horizontal"
android:foregroundTint="#color/purple_200"
android:foregroundTintMode="multiply"
android:requiresFadingEdge="vertical"
android:scrollbarDefaultDelayBeforeFade="10"
android:visibility="visible">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_columnSpan="4"
android:layout_columnWeight="12"
android:accessibilityLiveRegion="none"
android:orientation="vertical">
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="fill_parent"
android:layout_height="match_parent"></TableLayout>
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="#1DE9B6"
android:onClick="click2"
android:text="Generate"
android:textColor="#000000"
android:textSize="10dp" />
<EditText
android:id="#+id/simpleEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:digits="10"
android:hint="Number of coalitions appear here"
android:inputType="text"
android:minHeight="48dp"
android:textColor="#FF0000" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_columnSpan="12"
android:layout_columnWeight="12"
android:accessibilityLiveRegion="none"
android:inputType="textCapCharacters"
android:orientation="horizontal">
<Button
android:id="#+id/button4"
android:layout_width="25mm"
android:layout_height="wrap_content"
android:foregroundTint="#FF0000"
android:foregroundTintMode="src_over"
android:onClick="click4"
android:scrollbarDefaultDelayBeforeFade="4"
android:text="Increase"
android:textSize="11dp" />
<Button
android:id="#+id/button7"
android:layout_width="25mm"
android:layout_height="wrap_content"
android:foregroundTint="#FF0000"
android:foregroundTintMode="src_over"
android:onClick="click7"
android:scrollbarDefaultDelayBeforeFade="4"
android:text="Decrease"
android:textSize="11dp" />
</LinearLayout>
<Button
android:id="#+id/button5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#00E5FF"
android:backgroundTintMode="add"
android:onClick="click5"
android:text="Power indices" />
<TextView
android:id="#+id/textView6"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:text="Shapley and Banzhaf" />
</LinearLayout>
</ScrollView>
EDIT
<TextView
android:id="#+id/tvMarque"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:layout_gravity="center_horizontal"
android:fadingEdge="horizontal"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:padding="5dp"
android:textSize="16sp"
android:text="AHA"
android:visibility="visible" />
MainActivity.java
public class MainActivity extends AppCompatActivity {
double MOA;
TextView turretClicks;
boolean noMOA;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
turretClicks = (TextView) findViewById(R.id.turretClicks);
// Create an anonymous implementation of OnClickListener
View.OnClickListener btnClickCalc = new View.OnClickListener() {
#Override
public void onClick(View v) {
double clicks = (MOA * 4);
String toText = Double.toString(clicks);
turretClicks.setText(toText);
EditText range = (EditText) findViewById(R.id.rangeEntry);
String stringRange = range.getText().toString();
int finalRange = Integer.parseInt(stringRange);
if (finalRange <= 200) {
MOA = 0;
}
if (finalRange > 200 && finalRange <= 225) {
MOA = .5;
}
if (finalRange > 225 && finalRange <= 250) {
MOA = 1;
}
if (finalRange > 250 && finalRange <= 275) {
MOA = 1.65;
}
if (finalRange > 275 && finalRange <= 300) {
MOA = 2.25;
}
if (finalRange > 300 && finalRange <= 325) {
MOA = 2.8;
}
if (finalRange > 325 && finalRange <= 350) {
MOA = 3.5;
}
if (finalRange > 350 && finalRange <= 375) {
MOA = 4.0;
}
if (finalRange > 375 && finalRange <= 400) {
MOA = 4.75;
}
if (finalRange > 400 && finalRange <= 425) {
MOA = 5.50;
}
if (finalRange > 425 && finalRange <= 450) {
MOA = 6.25;
}
if (finalRange > 450 && finalRange <= 475) {
MOA = 7.0;
}
if (finalRange > 475 && finalRange <= 500) {
MOA = 7.5;
}
if (finalRange > 500 && finalRange <= 525) {
MOA = 8.25;
}
if (finalRange > 525 && finalRange <= 550) {
MOA = 9.0;
}
if (finalRange > 550 && finalRange <= 575) {
MOA = 9.75;
}
if (finalRange > 575 && finalRange <= 600) {
MOA = 10.5;
}
if (finalRange > 600 && finalRange <= 625) {
MOA = 11.5;
}
if (finalRange > 625 && finalRange <= 650) {
MOA = 12.25;
}
if (finalRange > 650 && finalRange <= 675) {
MOA = 13;
}
if (finalRange > 675 && finalRange <= 700) {
MOA = 14;
}
if (finalRange > 700) {
noMOA = true;
}
}
};
// Capture our button from layout
Button button = (Button) findViewById(R.id.btnClickCalc);
// Register the onClick listener with the implementation above
button.setOnClickListener(btnClickCalc);
final View.OnClickListener btnRecordRange = new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText range = (EditText) findViewById(R.id.rangeEntry);
final String recordableClicks = turretClicks.toString();
final String recordableRange = range.toString();
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("recordings.csv", Context.MODE_PRIVATE));
outputStreamWriter.write("Clicks" + " " + recordableClicks + "," + " " + "#Range" + recordableRange + "\n");
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
Toast.makeText(MainActivity.this, " Clicks # Range" + "\n" + "Successfully Recorded", Toast.LENGTH_SHORT).show();
}
};
// Capture our button from layout
Button recordRange = (Button) findViewById(R.id.btnRecordRange);
// Register the onClick listener with the implementation above
recordRange.setOnClickListener(btnRecordRange);
// Create an anonymous implementation of OnClickListener
final View.OnClickListener btnToRecorded = new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,RangeRecords.class));
}
};
// Capture our button from layout
Button showRecords = (Button) findViewById(R.id.btnToRecorded);
// Register the onClick listener with the implementation above
showRecords.setOnClickListener(btnToRecorded);
// Create an anonymous implementation of OnClickListener
}
}
RangeRecords.java
public class RangeRecords extends ListActivity {
public static TextView ListItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_recorded_ranges);
readFromFile("recordings.csv");
}
public String readFromFile(String fname) {
List<String> rangeList = new ArrayList();
String ret = "";
try {
InputStream inputStream = openFileInput(fname);
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString;
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString);
}
rangeList.add(stringBuilder.toString());
View linearLayout = findViewById(R.id.linLay);
for (int i = 0; i < rangeList.size(); i++) {
TextView value = new TextView(this);
value.setText(i);
value.setId(i);
value.setTextSize(20);
value.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
((LinearLayout) linearLayout).addView(value);
}
}
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
}
content_recorded_ranges.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="#+id/linLay">
<ListView android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
When I run this program on my phone, it works perfectly on the first activity. When I click the button to switch to the second activity, which should be displaying in TextViews the data I've recorded, the screen is just white. I can see the Android bar on the top where I see my service and battery life, etc, but it is even kinda blurred out a bit as if something is laying over the top of it.
The only reason I have the ListView is because the compiler demanded I have it in the code. I don't want/need it, but apparently the compiler thinks I do.
What am I doing wrong here? I want to display the recorded data on the second activity... so, we calculate the clicks on the turret, shoot the rifle, and record that data to a file if it's a good shot, then all we should have to do is come back to the second activity and view the data we've recorded from all our previous shots at varying ranges.
Anyone? Been at this all day.
Thanks!
EDIT
This is the code now:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_recorded_ranges"
tools:context="lol2dubs.stevemoa.recorded_ranges"
android:background="#fefefe">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="#+id/linLay">
</LinearLayout>
</RelativeLayout>
RangeRecords.java
public class RangeRecords extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_recorded_ranges);
readFromFile("recordings.csv");
}
public String readFromFile(String fname) {
List<String> rangeList = new ArrayList();
String ret = "";
try {
InputStream inputStream = openFileInput(fname);
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString;
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString);
}
rangeList.add(stringBuilder.toString());
View linearLayout = findViewById(R.id.linLay);
for (int i = 0; i < rangeList.size(); i++) {
TextView value = new TextView(this);
value.setText(i);
value.setId(i);
value.setTextSize(20);
value.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
((LinearLayout) linearLayout).addView(value);
}
}
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
}
Same thing is still occurring after removing the extends ListActivity and the ListView from the XML.
The ListView is demanded because you are extending ListActivity. Also, the ListView blocks your TextView so you couldn't see it.
However, you should use stick in using ListView since you are displaying multiple textviews with a dynamic number. See this for a tutorial.
If you don't want to use it then change
public class RangeRecords extends ListActivity
to
public class RangeRecords extends AppCompatActivity
Remove ListView on your layout
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="#+id/linLay">
</LinearLayout>
I am having difficulty making my layout to work...
What I want to do is have two spinners and a button below those and once the button is clicked, I display the results based on the values selected in the spinners.
-----------
| Spinner 1 |
-----------
-----------
| Spinner 2 |
-----------
-----------
| Button |
-----------
Result 1
Result 2
Result 3
Result 4
Result 5
I have tried to put the results in a ListView, but the problem I face is that once the button is clicked, I can see the repetition of Spinner1, Spinner2 and the Button itself multiple times.
The xml for the layout is as follows:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/country_arrays"
android:prompt="#string/country_prompt" />
<Spinner
android:id="#+id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/country_arrays"
android:prompt="#string/country_prompt" />
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/done" />
<LinearLayout
android:id="#+id/moreContent"
android:layout_width="match_parent"
android:visibility="visible"
android:orientation="vertical"
android:layout_height="wrap_content"
>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:textColor="#ff0000"
android:textSize="12sp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:contentDescription="#string/hello_world"
android:gravity="center_vertical"
android:text="#string/hello_world"
android:textColor="#0000ff"
android:textSize="12sp" />
</LinearLayout>
Can someone please advise where am I going wrong?
The code is as follows:
package ms.timetable;
import java.io.FileNotFoundException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;
import android.os.AsyncTask;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends ListActivity {
final Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void addListenerOnButton() {
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
RetreiveFeedTask rft = new RetreiveFeedTask();
rft.execute();
}
});
}
#SuppressLint("NewApi")
private class RetreiveFeedTask extends AsyncTask<Void, Void, String> {
TreeMap<String, String> _timetable = null;
#Override
protected String doInBackground(Void... arg0) {
// TODO Auto-generated method stub
_timetable = FetchTimetableInfo();
return null;
}
protected void onPostExecute(String str){
if (_timetable != null){
ArrayList<TimeTable> tarr = new ArrayList<TimeTable>();
Iterator<Entry<String, String>> it = _timetable.entrySet().iterator();
String toastText = "";
while (it.hasNext())
{
Map.Entry<String, String> pairs = (Map.Entry<String, String>)it.next();
String key = pairs.getKey();
String value = pairs.getValue();
toastText = toastText + key + " --- " + value + "\n";
//System.err.println(key + " --- " + value);
TimeTable tt = new TimeTable();
tt.set_line(value);
String [] tem = key.split("---");
tt.set_arrival(tem[1]);
tt.set_departure(tem[1]);
tarr.add(tt);
}
//Toast.makeText(context, toastText, Toast.LENGTH_LONG).show();
//tmap.add(_timetable);
setListAdapter((ListAdapter) new TimetableAdapter(getApplicationContext(), tarr));
}
}
private TreeMap<String, String> FetchTimetableInfo(){
Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
Spinner spinner2 = (Spinner) findViewById(R.id.spinner2);
String origin = (String) spinner1.getSelectedItem();
String destination = (String) spinner2.getSelectedItem();
//String val = String.valueOf(spinner1.getSelectedItem());
ArrayList<String> linesServOrigin = LineStation.GetServingLines(origin);
ArrayList<String> linesServDest = LineStation.GetServingLines(destination);
linesServOrigin.retainAll(linesServDest);
//ArrayList<String> preferredLines = linesServOrigin.re.retainAll(linesServDest);
Log.e(this.getClass().toString(), "Selected value is : " + linesServOrigin.get(0));
try
{
for (int k = 0; k < linesServOrigin.size(); k++)
{
String url = "http://tt.ptv.vic.gov.au/tt/XSLT_REQUEST?itdLPxx_lineMain=" + LineStation.GetLineMain(linesServOrigin.get(0)) + "&itdLPxx_lineID=" + LineStation.GetLineID(linesServOrigin.get(0)) + "&itdLPxx_output=html";
DataManager dm = new DataManager(url, getApplicationContext());
ArrayList<String> stationData = dm.GetStationsData();
ArrayList<ArrayList<String>> timetableData = dm.GetTimetableData();
ArrayList<String> originTimetable = null;
ArrayList<String> originTimetable1 = null;
ArrayList<String> destinationTimetable = null;
ArrayList<String> destinationTimetable1 = null;
int origPos = 0;
int destPos = 0;
int ctr = 0;
for (int i = 0; i < stationData.size(); i++)
{
if (stationData.get(i).equals(origin) || (origin + " - DEP").equals(stationData.get(i)))
{
//originTimetable = timetableData[i];
origPos = i;
}
else if (stationData.get(i).equals( destination) || (destination + " - ARR").equals(stationData.get(i)))
{
//destinationTimetable = timetableData[i];
destPos = i;
}
if (origPos != 0 && destPos != 0)
{
break;
}
}
if (origPos > destPos)
{
dm.SwitchDirection();
stationData = dm.GetStationsData();
timetableData = dm.GetTimetableData();
}
for (int i = stationData.size() - 1; i >= 0; i--)
{
if (stationData.get(i).equals(origin) || (origin + " - DEP").equals(stationData.get(i)))
{
if (originTimetable == null)
{
originTimetable = timetableData.get(i);
}
else if (originTimetable1 == null)
{
originTimetable1 = timetableData.get(i);
}
}
else if (stationData.get(i).equals(destination) || (destination + " - ARR").equals(stationData.get(i)))
{
if (destinationTimetable == null)
{
destinationTimetable = timetableData.get(i);
}
else if (destinationTimetable1 == null)
{
destinationTimetable1 = timetableData.get(i);
}
}
}
TreeMap<String, String> ttable = new TreeMap<String, String>();
if (originTimetable != null && destinationTimetable != null)
{
//int curtime = Integer.parseInt(DateTime.Now.ToString("HHmm", CultureInfo.CurrentCulture));
String temp = new SimpleDateFormat("HHmm").format(Calendar.getInstance().getTime());
int curtime =Integer.parseInt(temp);
System.err.println("Origin timetable size = " + originTimetable.size());
System.err.println("Destination timetable size = " + destinationTimetable.size());
for (int j = 0; j < originTimetable.size(); j++)
{
if (Integer.parseInt((originTimetable.get(j))) > curtime)
{
if (Integer.parseInt((destinationTimetable.get(j))) == -1)
{
if (destinationTimetable1 == null || (Integer.parseInt(destinationTimetable1.get(j)) == -1))
{
continue;
}
}
else if (destinationTimetable1 != null && Integer.parseInt(destinationTimetable1.get(j)) == -1)
{
if (destinationTimetable == null || (Integer.parseInt(destinationTimetable.get(j)) == -1))
{
continue;
}
}
ctr++;
if (destinationTimetable1 != null)
{
if (Integer.parseInt(originTimetable.get(j)) < Integer.parseInt(destinationTimetable1.get(j)))
{
ttable.put(originTimetable.get(j) + " --- " + destinationTimetable1.get(j), linesServOrigin.get(k));
}
}
else
{
if (Integer.parseInt(originTimetable.get(j)) < Integer.parseInt(destinationTimetable.get(j)))
{
ttable.put(originTimetable.get(j) + " --- " + destinationTimetable.get(j), linesServOrigin.get(k));
}
}
if (ctr == 5)
{
break;
}
}
}
ctr = 0;
if (originTimetable1 != null)
{
for (int j = 0; j < originTimetable1.size(); j++)
{
if (originTimetable1 != null && Integer.parseInt(originTimetable1.get(j)) > curtime)
{
if (Integer.parseInt(destinationTimetable.get(j)) == -1)
{
if (destinationTimetable1 == null || (Integer.parseInt(destinationTimetable1.get(j)) == -1))
{
continue;
}
}
else if (destinationTimetable1 != null && Integer.parseInt(destinationTimetable1.get(j)) == -1)
{
if (destinationTimetable == null || (Integer.parseInt(destinationTimetable.get(j))) == -1)
{
continue;
}
}
ctr++;
if (destinationTimetable1 != null)
{
if (Integer.parseInt(originTimetable1.get(j)) < Integer.parseInt(destinationTimetable1.get(j)))
{
ttable.put(originTimetable1.get(j) + " --- " + destinationTimetable1.get(j), linesServOrigin.get(k));
}
}
else
{
if (Integer.parseInt(originTimetable1.get(j)) < Integer.parseInt(destinationTimetable.get(j)))
{
ttable.put(originTimetable1.get(j) + " --- " + destinationTimetable.get(j), linesServOrigin.get(k));
}
}
if (ctr == 5)
{
break;
}
}
}
}
Iterator<Entry<String, String>> it = ttable.entrySet().iterator();
//foreach (KeyValuePair<String, List<String>> item in lineStations)
while (it.hasNext())
{
Map.Entry<String, String> pairs = (Map.Entry<String, String>)it.next();
String key = pairs.getKey();
String value = pairs.getValue();
System.err.println(key + " --- " + value);
}
return ttable;
}
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
class TimeTable{
private String _departure, _arrival, _line;
public TimeTable(){
}
public TimeTable(String departure, String arrival, String line){
_departure = departure;
_arrival = arrival;
_line = line;
}
public String get_departure() {
return _departure;
}
public void set_departure(String _departure) {
this._departure = _departure;
}
public String get_arrival() {
return _arrival;
}
public void set_arrival(String _arrival) {
this._arrival = _arrival;
}
public String get_line() {
return _line;
}
public void set_line(String _line) {
this._line = _line;
}
}
}
The adapter is as follows:
package ms.timetable;
import java.util.ArrayList;
import ms.timetable.MainActivity.TimeTable;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class TimetableAdapter extends ArrayAdapter<TimeTable>{
private final Context context;
private final ArrayList<TimeTable> values;
public TimetableAdapter(Context context, ArrayList<TimeTable> values){
super(context, R.layout.activity_main, values);
this.context = context;
this.values = values;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.activity_main, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.textView1);
TextView textView2 = (TextView) rowView.findViewById(R.id.textView2);
//System.err.println("Position is : "+position);
TimeTable tt = values.get(position);
textView.setText(tt.get_departure());
textView2.setText(tt.get_arrival());
return rowView;
}
}
The problem is due to
View rowView = inflater.inflate(R.layout.activity_main, parent, false);
in getView() method.
You are inflating whole activity_main in a row and then adding it to a listview.
Put a row for results in separate xml instead of activity_main. So you will have a new xml file say, row.xml which will contain:
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:textColor="#ff0000"
android:textSize="12sp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:contentDescription="#string/hello_world"
android:gravity="center_vertical"
android:text="#string/hello_world"
android:textColor="#0000ff"
android:textSize="12sp" />
So you will have to inflate as
View rowView = inflater.inflate(R.layout.row, parent, false);
And then add the generated rows in the listview which is in activity_main.xml.
So your problem will be solved. Hope it helps.
I have a problem that, I am adding listview in LinearLayout dynamically through code and set the EndlessAdapter into that, Data is shown correctly but we are unable to scroll from top to bottom in the list. I don't know why? please suggest me any solution regarding the same.
Code:
public void setValuesInCategoryChild(String url, final String filter, final String from, final String to) {
if (isOnline()) {
final ProgressDialog dialog = ProgressDialog.show(ResearchList.this, "Research List ", "Please wait... ", true);
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
// System.out.println("The id after Save:"+id.get(0).toString());
// catagory.addAll(keyword_vector1);
linear_Category_Child.setVisibility(View.GONE);
linear_Category_Child_Child.setVisibility(View.VISIBLE);
// tv_Child_Header.setText("Volvo");
tv_CategoryChildHeader.setText(from);
setHeaderImage(tv_CategoryChildHeader.getText().toString());
System.out.println("The size of Cat Display names:" + coll.getDisplayNames().size());
System.out.println("The size of Cat Images:" + coll.getImages().size());
System.out.println("The size of Cat price:" + coll.getPrice().size());
System.out.println("The size of Cat Year:" + coll.getYears().size());
System.out.println("The size of Cat Rating:" + coll.getRating().size());
System.out.println("The size of Cat Mpg:" + coll.getMpg().size());
setHeaderImage(tv_CategoryChildHeader.getText().toString());
if(coll.getDisplayNames().size()!=0) {
lvCategory = new ListView(ResearchList.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
lvCategory.setLayoutParams(params);
// Adapter for MPG Search
demoAdapterCat = new DemoAdapterCat();
lvCategory.setAdapter(demoAdapterCat);
layout_ResearchList_BrandList.addView(lvCategory);
Utility.setListViewHeightBasedOnChildren(lvCategory);
}else {
/*lvCategory.invalidate();
lvCategory.setAdapter(null);*/
AlertDialog.Builder builder = new Builder(ResearchList.this);
builder.setTitle("Attention!");
builder.setMessage("No Data Available for the Particular Search.");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
builder.create().show();
}
/*Utility util = new Utility();
util.setListViewHeightBasedOnChildren(lvCategory);*/
dialog.dismiss();
}
};
final Thread checkUpdate = new Thread() {
public void run() {
try {
String sortEncode = URLEncoder.encode("mpg");
String filterEncode = URLEncoder.encode(filter);
String clientEncode = URLEncoder.encode("10030812");
String fromEncode = URLEncoder.encode(from);
String toEncode = URLEncoder.encode(to);
String catUrl = "/v1/vehicles/get-make-models.json?sort=" + sortEncode + "&filter=" + filterEncode + "&client-id=" + clientEncode + "&from=" + fromEncode;
genSig = new GetSignature(catUrl, "acura");
try {
signature = genSig.getUrlFromString();
} catch (InvalidKeyException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// jsonString =
// getJsonSring("http://api.highgearmedia.com/v1/vehicles/get-models.json?make=acura&client-id=10030812&signature=LWQbdAlJVxlXZ1VO2mfqAA==");
// String signatureEncode =
// URLEncoder.encode(signature);
String urlEncode = URLEncoder.encode(catUrl + "&signature=" + signature);
jsonString = getJsonSring("http://apibeta.highgearmedia.com" + catUrl + "&signature=" + signature);
System.out.println("The json category:===>" + jsonString);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JsonParse json = new JsonParse(jsonString);
json.parseCat();
LIST_SIZE = coll.getDisplayNames().size();
for (int i = 0; i <= BATCH_SIZE; i++) {
// countriesSub.add(COUNTRIES[i]);
countriesSubCat.add(coll.getDisplayNames().get(i));
imagesSubCat.add(coll.getImages().get(i));
YearSubCat1.add(coll.getYears().get(i));
YearSubCat2.add(coll.getYears().get(i + 1));
mpgSubCat1.add(coll.getMpg().get(i));
mpgSubCat2.add(coll.getMpg().get(i + 1));
priceSubCat1.add(coll.getPrice().get(i));
priceSubCat2.add(coll.getPrice().get(i + 1));
ratingSubCat1.add(coll.getRating().get(i));
ratingSubCat2.add(coll.getRating().get(i + 1));
}
setLastOffset(BATCH_SIZE);
handler.sendEmptyMessage(0);
}
};
checkUpdate.start();
} else {
AlertDialog.Builder builder = new Builder(ResearchList.this);
builder.setTitle("Attention!");
builder.setMessage("Network Connection unavailable.");
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
builder.create().show();
}
}
Layout:
<LinearLayout
android:id="#+id/linear_ResearchListCategoryChild_Child"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:visibility="gone" >
<RelativeLayout
android:id="#+id/linear_ResearchListCategoryChild_Child_HeaderBlock"
android:layout_width="fill_parent"
android:layout_height="40dip"
android:background="#drawable/catagory_bar"
android:orientation="horizontal" >
<TextView
android:id="#+id/tv_ResearchListCategoryChild_Child_Header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:text="Work in Progress"
android:textColor="#ffffff"
android:textStyle="bold" android:layout_marginLeft="60dip"/>
<ImageView
android:id="#+id/img_ResearchListCategory_ChildHeader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="10dip"
android:src="#drawable/up_arrow" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:src="#drawable/list_arrow_up" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/linear_ResearchListCategoryChild_Child_Header"
android:layout_width="fill_parent"
android:layout_height="40dip"
android:background="#drawable/nav_bg"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="5dip"
android:clickable="true"
android:text="Highest Rated"
android:textColor="#ffffff"
android:textStyle="bold" android:gravity="center"/>
<TextView
android:id="#+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView5"
android:layout_alignBottom="#+id/textView5"
android:layout_marginLeft="30dp"
android:layout_toRightOf="#+id/textView5"
android:clickable="true"
android:text="A-Z"
android:textColor="#ffffff"
android:textStyle="bold" android:gravity="center"/>
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView6"
android:layout_alignBottom="#+id/textView6"
android:layout_marginLeft="40dp"
android:layout_toRightOf="#+id/textView6"
android:clickable="true"
android:text="Price"
android:textColor="#ffffff"
android:textStyle="bold" android:gravity="center"/>
<TextView
android:id="#+id/textView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView7"
android:layout_alignBottom="#+id/textView7"
android:layout_alignParentRight="true"
android:layout_marginRight="14dp"
android:clickable="true"
android:text="MPG"
android:textColor="#ffffff"
android:textStyle="bold" android:gravity="center"/>
</RelativeLayout>
<!--
<RelativeLayout
android:id="#+id/relative_down_arrow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="visible"
>
</RelativeLayout>
-->
<LinearLayout
android:id="#+id/linearArrowLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:visibility="visible">
<ImageView
android:id="#+id/Highly_rated"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="51dp"
android:src="#drawable/selector_arrow"
android:visibility="invisible" />
<ImageView
android:id="#+id/AZ_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="78dp"
android:src="#drawable/selector_arrow"
android:visibility="invisible" />
<ImageView
android:id="#+id/Price_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="59dp"
android:src="#drawable/selector_arrow"
android:visibility="invisible" />
<ImageView
android:id="#+id/MPG"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="55dp"
android:src="#drawable/selector_arrow"
android:visibility="invisible" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="12dip"
android:layout_marginRight="12dip" android:background="#ffffff" android:id="#+id/layout_ResearchList_BrandList">
</LinearLayout>
</LinearLayout>
DemoAdapterCat:
class DemoAdapterCat extends EndlessAdapter {
ImageLoader image = new ImageLoader(ResearchList.this);
private RotateAnimation rotate = null;
ArrayList<String> tempListNamesCat = new ArrayList<String>();
ArrayList<String> tempListImagesCat = new ArrayList<String>();
ArrayList<String> tempListYearCat1 = new ArrayList<String>();
ArrayList<String> tempListYearCat2 = new ArrayList<String>();
ArrayList<String> tempListmpgCat1 = new ArrayList<String>();
ArrayList<String> tempListmpgCat2 = new ArrayList<String>();
ArrayList<String> tempListpriceCat1 = new ArrayList<String>();
ArrayList<String> tempListpriceCat2 = new ArrayList<String>();
ArrayList<String> tempListRatingCat1 = new ArrayList<String>();
ArrayList<String> tempListRatingCat2 = new ArrayList<String>();
DemoAdapterCat() {
super(new CategoryListLazyAdapter(ResearchList.this,
countriesSubCat, imagesSubCat, YearSubCat1, YearSubCat2,
mpgSubCat1, mpgSubCat2, priceSubCat1, priceSubCat2,
ratingSubCat1, ratingSubCat2));
/*Utility util = new Utility();
util.setListViewHeightBasedOnChildren(lvCategory);*/
rotate = new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF,
0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
rotate.setDuration(600);
rotate.setRepeatMode(Animation.RESTART);
rotate.setRepeatCount(Animation.INFINITE);
}
/*
* #Override public int getCount() { return
* brandList.getDisplayNames().size(); //return count+=10; }
*/
#Override
protected View getPendingView(ViewGroup parent) {
row = getLayoutInflater().inflate(R.layout.categorylist, null);
child = row.findViewById(R.id.tv_CategoryItem_Name);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_MPG1);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_MPG2);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Price1);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Price2);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Rating1);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Rating2);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Year1);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Year2);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.linear_CategoryList_itemlayer1);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.linear_CategoryList_itemlayer2);
child.setVisibility(View.GONE);
/*
* child = row.findViewById(R.id.img_CategoryItem);
* child.setVisibility(View.GONE); child =
* row.findViewById(R.id.img_CategoryItem_Arrow);
* child.setVisibility(View.GONE);
*/
/*
* child = row.findViewById(R.id.linear_main_MPG);
* child.setVisibility(View.GONE);
*/
child = row.findViewById(R.id.throbber);
child.setVisibility(View.VISIBLE);
child.startAnimation(rotate);
return (row);
}
#Override
protected boolean cacheInBackground() {
//count += 10;
SystemClock.sleep(100000);
tempListNamesCat.clear();
tempListImagesCat.clear();
tempListmpgCat1.clear();
tempListmpgCat2.clear();
tempListpriceCat1.clear();
tempListpriceCat2.clear();
tempListYearCat1.clear();
tempListYearCat2.clear();
tempListRatingCat1.clear();
tempListRatingCat2.clear();
// countriesSubCat.clear();
// imagesSubCat.clear();
// YearSubCat1.clear();
// YearSubCat2.clear();
// mpgSubCat1.clear();
// mpgSubCat2.clear();
// priceSubCat1.clear();
// priceSubCat2.clear();
// ratingSubCat1.clear();
// ratingSubCat2.clear();
int lastOffset = getLastOffset();
if (lastOffset < LIST_SIZE) {
int limit = lastOffset + BATCH_SIZE;
for (int i = (lastOffset + 1); (i <= limit && i < LIST_SIZE); i++) {
tempListNamesCat.add(coll.getDisplayNames().get(i));
tempListImagesCat.add(coll.getImages().get(i));
tempListmpgCat1.add(coll.getMpg().get(i));
tempListmpgCat2.add(coll.getMpg().get(i + 1));
tempListpriceCat1.add(coll.getPrice().get(i));
tempListpriceCat2.add(coll.getPrice().get(i + 1));
tempListRatingCat1.add(coll.getRating().get(i));
tempListRatingCat2.add(coll.getRating().get(i + 1));
tempListYearCat1.add(coll.getYears().get(i));
tempListYearCat2.add(coll.getYears().get(i + 1));
}
setLastOffset(limit);
if (limit < LIST_SIZE) {
// return true;
return (getWrappedAdapter().getCount() < coll
.getDisplayNames().size());
} else {
return false;
}
} else {
return false;
}
}
#Override
protected void appendCachedData() {
#SuppressWarnings("unchecked")
// Activity activity = this;
// ArrayAdapter<String> arrAdapterNew =
// (ArrayAdapter<String>)getWrappedAdapter();
CategoryListLazyAdapter arrAdapterNewCategory = (CategoryListLazyAdapter) getWrappedAdapter();
// int listLen = tempList.size();
// int listLen = tempListNames.size();
countriesSubCat.addAll(tempListNamesCat);
imagesSubCat.addAll(tempListImagesCat);
mpgSubCat1.addAll(tempListmpgCat1);
mpgSubCat2.addAll(tempListmpgCat2);
priceSubCat1.addAll(tempListpriceCat1);
priceSubCat2.addAll(tempListpriceCat2);
ratingSubCat1.addAll(tempListRatingCat1);
ratingSubCat2.addAll(tempListRatingCat2);
YearSubCat1.addAll(tempListYearCat1);
YearSubCat2.addAll(tempListYearCat2);
arrAdapterNewCategory.notifyDataSetChanged();
/*Utility util = new Utility();
util.setListViewHeightBasedOnChildren(lvCategory);*/
/*
* for(int i=0; i<listLen; i++){ //
* arrAdapterNew.add(tempList.get(i)); }
*/
}
}
Thanks in adavance.
Try adding a ScrollView in the xml file.
Here are some links which tell about video recording:
How can I capture a video recording on Android?
https://github.com/churnlabs/android-ffmpeg-sample
and there are also many links which tell about video recording but got no any clue how to use the remote IP camera to record video.
By using different samples on stackoverflow I become able to take picture and save on sdcard but couldn't record video.
If any one has any idea or code along with required files I will be thankful.
For example the url I am using where the IP camera is available is given below:
http://trackfield.webcam.oregonstate.edu/axis-cgi/mjpg/video.cgi?resolution=800x600&%3bdummy=1333689998337
Here is the layout code:
<RelativeLayout
android:id="#+id/LinearLayout02"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/logo"
android:layout_alignParentTop="true"
android:layout_weight="1" >
<ImageButton
android:id="#+id/btnCam"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:src="#drawable/camera_icon" >
</ImageButton>
<ImageButton
android:id="#+id/btnVideo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:src="#drawable/camera_icon" >
</ImageButton>
</RelativeLayout>
<LinearLayout
android:id="#+id/LinearLayout03"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/LinearLayout01"
android:layout_below="#+id/LinearLayout02"
android:layout_weight="1" >
<RelativeLayout
android:id="#+id/RelativeLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#ffffff" >
<view
android:id="#+id/mv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
class="com.apps.GrahamConst.MjpegView" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_weight="1"
android:background="#drawable/navbar" >
<ImageButton
android:id="#+id/btnPrevious"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:layout_weight="1"
android:background="#null"
android:src="#drawable/previous" >
</ImageButton>
<ImageButton
android:id="#+id/btnMain"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:layout_weight="1"
android:background="#null"
android:src="#drawable/main" >
</ImageButton>
<ImageButton
android:id="#+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:layout_weight="1"
android:background="#null"
android:src="#drawable/next" >
</ImageButton>
</LinearLayout>
</RelativeLayout>
Here is my Activity
public class CameraDetails2 extends Activity implements OnClickListener {
private MediaScannerConnection m_pScanner;
String drawable = null;
private MjpegView mv;
private ProgressDialog dialog;
private HashMap<String, String> item;
private int id = -1;
private WindowManager winMan;
boolean recording = false;
MediaRecorder recorder;
int bytearraysize = 0;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
winMan = (WindowManager) getApplicationContext().getSystemService(
Context.WINDOW_SERVICE);
if (winMan != null) {
int orientation = winMan.getDefaultDisplay().getOrientation();
if (orientation == 0) {
// Portrait
setContentView(R.layout.cameradetails);
} else if (orientation == 1) {
// Landscape
setContentView(R.layout.cameradetailsl);
}
}
Bundle b = getIntent().getExtras();
ImageButton b1 = (ImageButton) findViewById(R.id.btnNext);
b1.setOnClickListener(this);
ImageButton b2 = (ImageButton) findViewById(R.id.btnMain);
b2.setOnClickListener(this);
ImageButton b3 = (ImageButton) findViewById(R.id.btnPrevious);
b3.setOnClickListener(this);
ImageButton b4 = (ImageButton) findViewById(R.id.btnCam);
b4.setOnClickListener(this);
ImageButton b5 = (ImageButton) findViewById(R.id.btnVideo);
b5.setOnClickListener(this);
id = Integer.valueOf(b.get("id").toString());
item = listarrayadapter.cameraList.get(Integer.valueOf(id));
mv = (MjpegView) findViewById(R.id.mv);
try {
getVal(item.get("cameraLink"));
// getVal("http://trackfield.webcam.oregonstate.edu/axis-cgi/mjpg
/video.cgi?resolution=800x600&%3bdummy=1333689998337");
} catch (Exception e) {
e.printStackTrace();
mv.setBackgroundResource(R.drawable.offline);
}
}
#Override
protected void onResume() {
// if(recording)
// {
// getVal("http://trackfield.webcam.oregonstate.edu/axis-cgi/mjpg
/video.cgi?resolution=800x600&%3bdummy=1333689998337");
// }
super.onResume();
}
public void onPause() {
super.onPause();
dialog.dismiss();
mv.stopPlayback();
}
private void getVal(final String url) {
Log.i("URL===", url);
updateButtons();
dialog = ProgressDialog.show(this, null, null, true);
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
dialog.dismiss();
}
};
Thread checkUpdate = null;
checkUpdate = new Thread() {
public void run() {
mv.setSource(MjpegInputStream.read(url));
mv.setDisplayMode(MjpegView.SIZE_FULLSCREEN);
handler.sendEmptyMessage(0);
}
};
checkUpdate.start();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int btn = v.getId();
if (btn == R.id.btnMain) {
Intent intent = new Intent();
intent.setClass(CameraDetails2.this, CamerasList.class);
startActivity(intent);
finish();
}
if (btn == R.id.btnNext) {
id += 1;
Intent myintent = new Intent(CameraDetails2.this,
CameraDetails.class);
myintent.putExtra("id", id);
startActivity(myintent);
finish();
}
if (btn == R.id.btnPrevious) {
id -= 1;
Intent myintent = new Intent(CameraDetails2.this,
CameraDetails.class);
myintent.putExtra("id", id);
startActivity(myintent);
finish();
}
if (btn == R.id.btnCam) {
if (mv != null) {
Date dt = new Date();
int years = dt.getYear();
int month = dt.getMonth();
int day = dt.getDay();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
final String filename = years + "" + month + "" + day + ""
+ hours + "" + minutes + "" + seconds;
try {
Bitmap image = MjpegView.savebmp;
File SDCardRoot =
Environment.getExternalStorageDirectory();
FileOutputStream fileOutputStream = null;
fileOutputStream = new FileOutputStream(
SDCardRoot.toString() + "/" +
filename + ".jpg");
BufferedOutputStream bos = new
BufferedOutputStream(
fileOutputStream);
int quality = 95;
image.compress(CompressFormat.JPEG, quality, bos);
final String szFile = SDCardRoot.toString() + "/"
+ filename + ".jpg";
m_pScanner = new MediaScannerConnection(this,
new MediaScannerConnectionClient()
{
public void
onMediaScannerConnected() {
m_pScanner
.scanFile(szFile, null /* mimeType */);
}
public void
onScanCompleted(String path, Uri uri) {
if
(path.equals(szFile)) {
CameraDetails2.this
.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(
getApplicationContext(),
"Image Saved.",
Toast.LENGTH_LONG)
.show();
}
});
m_pScanner.disconnect();
}
}
});
m_pScanner.connect();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
if (btn == R.id.btnVideo) {
if (recording) {
// stop and save
recording = false;
MjpegInputStream.isrecording = false;
List<byte[]> bytelist = new ArrayList<byte[]>();
ArrayList<ByteArrayOutputStream> byteArrayStream =
MjpegInputStream.byteArrayStream;
for (int i = 0; i < byteArrayStream.size(); i++) {
byte[] templist
=byteArrayStream.get(i).toByteArray();
bytelist.add(templist);
}
for (int j = 0; j < bytelist.size(); j++) {
bytearraysize += bytelist.get(j).length;
}
byte[] totalbytes = new byte[bytearraysize];
int f = 0;
for (int j = 0; j < bytelist.size(); j++) {
for (int a = 0; a < bytelist.get(j).length; a++) {
totalbytes[f] = bytelist.get(j)[a];
f++;
}
}
Log.e("num of bytes", "" + totalbytes.length);
// Byte[] bytes = bytelist.toArray(new
//Byte[bytelist.size()]);
try {
writeToFile(totalbytes, "" +
System.currentTimeMillis());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
recording = true;
MjpegInputStream.isrecording = true;
// onResume();
// start recording
}
// recorder=new MediaRecorder();
// try {
// recorder.prepare();
// } catch (IllegalStateException e) {
// e.printStackTrace();
// finish();
// } catch (IOException e) {
// e.printStackTrace();
// finish();
// }
//
// //recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
// // recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
//
// //
// //
// // CamcorderProfile cpHigh = CamcorderProfile
// // .get(CamcorderProfile.QUALITY_HIGH);
// // recorder.setProfile(cpHigh);
// recorder.setVideoSource(mv.getId());
// recorder.setOutputFile("/sdcard/videocapture_example.mp4");
// recorder.setMaxDuration(50000); // 50 seconds
// recorder.setMaxFileSize(5000000); // Approximately 5 megabytes
}
}
public void writeToFile(byte[] bytes, String videoname) throws IOException {
try {
Log.e("num of bytes to be saved", "" + bytes.length);
String path = "/sdcard/" + videoname + ".mp4";
FileOutputStream stream = new FileOutputStream(path);
stream.write(bytes);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private void updateButtons() {
ImageButton btnNext = (ImageButton) findViewById(R.id.btnNext);
ImageButton btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);
if (id == 0) {
btnPrevious.setEnabled(false);
} else {
btnPrevious.setEnabled(true);
}
if (id == listarrayadapter.cameraList.size() - 1) {
btnNext.setEnabled(false);
} else {
btnNext.setEnabled(true);
}
}
}