I'm trying to return an ArrayList from onPostExecute method of AsyncTask in Main Activity. I'm assigning returned ArrayList to the searchedText ArrayList of main activity. I'm not able to get elements of searchedText ArrayList in btnSearch onClickListener. Please let me know what is wrong in the code.
package com.example.dharak029.hw3_group09;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.io.InputStream;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
EditText textIn;
ImageButton buttonAdd;
LinearLayout container;
ArrayList<String> wordList;
byte[] buffer;
String text;
ArrayList<String> searchText;
ArrayList<String> searchedText;
int keywordCount=0;
void setResult(ArrayList<String> searchedText){
this.searchedText = searchedText;
Log.d("result",""+searchedText.size());
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textIn = (EditText)findViewById(R.id.textin);
buttonAdd = (ImageButton)findViewById(R.id.add);
container = (LinearLayout)findViewById(R.id.container);
wordList = new ArrayList<String>();
searchText = new ArrayList<String>();
try {
InputStream is = getAssets().open("textfile.txt");
int size = is.available();
buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
int startIndex = 0;
for(int i=0;i<text.length()/30;i++){
searchText.add(text.substring(startIndex,startIndex+30));
startIndex = startIndex+30;
}
}
catch (Exception e){
}
findViewById(R.id.btnSearch).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(String word: wordList){
new DoWork(MainActivity.this).execute(word);
}
Intent intent = new Intent(MainActivity.this,WordsFound.class);
intent.putExtra("searchResults",searchedText);
startActivity(intent);
}
});
buttonAdd.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if (keywordCount <= 20) {
LayoutInflater layoutInflater =
(LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View addView = layoutInflater.inflate(R.layout.row, null);
final TextView textOut = (TextView) addView.findViewById(R.id.textout);
textOut.setText(textIn.getText().toString());
wordList.add(textIn.getText().toString());
ImageButton buttonRemove = (ImageButton) addView.findViewById(R.id.remove);
final View.OnClickListener thisListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
((LinearLayout) addView.getParent()).removeView(addView);
wordList.remove(textOut.getText().toString());
listAllAddView();
keywordCount--;
}
};
buttonRemove.setOnClickListener(thisListener);
container.addView(addView);
listAllAddView();
keywordCount++;
}
}
});
}
private void listAllAddView(){
int childCount = container.getChildCount();
for(int i=0; i<childCount; i++){
View thisChild = container.getChildAt(i);
}
}
class DoWork extends AsyncTask<String,Integer,ArrayList<String>>{
ArrayList<String> searchResult = new ArrayList<String>();
ProgressBar progress;
MainActivity activity;
public DoWork(MainActivity activity) {
this.activity = activity;
}
#Override
protected ArrayList<String> doInBackground(String... params) {
for(int i=0;i<searchText.size();i++){
String text = searchText.get(i);
if(text.contains(params[0]))
searchResult.add(text);
}
Log.d("demo",""+searchResult.size());
return searchResult;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(ArrayList<String> aVoid) {
super.onPostExecute(aVoid);
activity.setResult(aVoid);
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
}
}
You can't put ArrayList in extras by putExtra() you have to use putStringArrayListExtra(). Try below code.
Intent intent = new Intent(MainActivity.this,WordsFound.class);
intent.putStringArrayListExtra("searchResults",searchedText);
startActivity(intent);
The problem is in the following code:
findViewById(R.id.btnSearch).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(String word: wordList){
new DoWork(MainActivity.this).execute(word);
}
Intent intent = new Intent(MainActivity.this, WordsFound.class);
intent.putExtra("searchResults",searchedText);
startActivity(intent);
}
});
Let's dissect the code. No problem with the following code. It's the usual code for click listener:
findViewById(R.id.btnSearch).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
...
}
Now, we look into the body code, from the following code:
for(String word: wordList){
new DoWork(MainActivity.this).execute(word);
}
We knew that DoWork is an AsyncTask which is doing an asynchronous process. So, the next code will be executed eventhough the DoWork haven't finished its process.
Let's see the next code:
Intent intent = new Intent(MainActivity.this, WordsFound.class);
intent.putExtra("searchResults", searchedText);
startActivity(intent);
Here you put the extra from searchedText variable which is only initialized in onCreate with:
searchText = new ArrayList<String>();
So, you'll always have the empty list when setting the extra.
To overcome the empty list issue, you need to send the extra only after the DoWork is finished doing its job. You can try calling the Intent inside the setResult
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 5 years ago.
I made an incredibly simple app but for some reason it's just crashing. The first page is a simple login screen however the moment I click login it just crashes. The strange part is that there's not even any heavy code to make it do anything strange like that; I'm just making it travel between activities so far.
The main activity
package com.example.philip.lottery1;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class LoginActivity extends AppCompatActivity {
Button loginButton;
EditText userNameField;
EditText passwordField;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginButton = (Button) findViewById(R.id.loginButton);
userNameField = (EditText) findViewById(R.id.userNameField);
passwordField = (EditText) findViewById(R.id.passwordField);
final String userName = userNameField.getText().toString();
String password = passwordField.getText().toString();
loginButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), CreateTicket.class);
intent.putExtra("ClerkID", userName);
startActivity(intent);
}
});
}
}
The activity it leads to
package com.example.philip.lottery1;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.Random;
public class CreateTicket extends AppCompatActivity {
private Button randomButton;
private Button OKButton;
private Button searchButton;
private EditText[] lottoNumberFields;
private int[] lottoNumbers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_ticket);
lottoNumberFields = new EditText[5];
lottoNumberFields[1] = (EditText)findViewById(R.id.num1);
lottoNumberFields[2] = (EditText)findViewById(R.id.num2);
lottoNumberFields[3] = (EditText)findViewById(R.id.num3);
lottoNumberFields[4] = (EditText)findViewById(R.id.num4);
lottoNumberFields[5] = (EditText)findViewById(R.id.num5);
randomButton = (Button) findViewById(R.id.randomButton);
OKButton = (Button) findViewById(R.id.OKButton);
searchButton = (Button) findViewById(R.id.searchButton);
randomButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
randommize();
}
});
OKButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
createTicket();
}
});
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
search();
}
});
}
private void search()
{
//insert code here
Intent intent = new Intent (getBaseContext(),TicketActivity.class);
startActivity(intent);
}
private void randommize()
{
for (int i = 0 ; i < 5 ; i ++)
{
Random random = new Random();
int num = random.nextInt(49) + 1;
lottoNumberFields[i].setText(num+"");
}
}
private void createTicket()
{
for (int i = 0; i < 5; i++)
{
lottoNumbers[i] = Integer.parseInt(lottoNumberFields[i].getText().toString());
}
Intent intent = new Intent(getBaseContext(), FinalActivity.class);
intent.putExtra("lottoNumbers",lottoNumbers);
startActivity(intent);
}
}
Your lottoNumberFields array is of length 5, but you are going from 1 to 5 index values for it, instead of 0 to 4. Change the code as below:
lottoNumberFields = new EditText[5];
lottoNumberFields[0] = (EditText)findViewById(R.id.num1);
lottoNumberFields[1] = (EditText)findViewById(R.id.num2);
lottoNumberFields[2] = (EditText)findViewById(R.id.num3);
lottoNumberFields[3] = (EditText)findViewById(R.id.num4);
lottoNumberFields[4] = (EditText)findViewById(R.id.num5);
I am creating an app which calculates the total marks & percentage and shows the result in the next activity called ResultActvity. I am using same ResultActivity for showing result for 1st yr student & 2nd yr student marks, everything works fine when it come to show the result for 1st yr students but when it comes to show the result for second yr students it is only showing total marks but no % is shown. I am a newbie to android development please help me in fixing this. Thank You :).
FIRSTACTIVITY
package com.jntuhcalculator.anu.jntuhcalculator;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
/**
* Created by anu on 18/9/15.
*/
public class FirstMarks extends Activity {
TextView tv_Subjects1, tv_Internal1, tv_External1;
EditText et_Int_Eng, et_Int_M1, et_Int_MM, et_Int_Phy, et_Int_Chem, et_Int_Cp, et_Int_ElcsLab, et_Int_EpLab, et_Int_ItLab, et_Int_Draw;
EditText et_Ext_Eng, et_Ext_M1, et_Ext_MM, et_Ext_Phy, et_Ext_Chem, et_Ext_Cp, et_Ext_ElcsLab, et_Ext_EpLab, et_Ext_ItLab, et_Ext_Draw;
Button btn_Cal1, btn_Ok1;
int IEng,IM1,IMM,IEPhy,IEChem,ICp,IEDraw,IELCS_Lab,IEP_LAB,IIT_LAB;
int EEng,EM1,EMM,EEPhy,EEChem,ECp,EEDraw,EELCS_Lab,EEP_LAB,EIT_LAB;
int ITotal1,ETotal1,Total1;
float Percentage1;
String f1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.marks_1);
//INITIALISING VIEWS.
//INITIALISING TEXT VIEWS.
tv_Subjects1 = (TextView) findViewById(R.id.tv_Subject1);
tv_Internal1 = (TextView) findViewById(R.id.tv_Internal1);
tv_External1 = (TextView) findViewById(R.id.tv_External1);
//INITIALISING EDIT TEXT.
//INTERNAL
et_Int_Eng = (EditText) findViewById(R.id.et_Int_Eng);
et_Int_M1 = (EditText) findViewById(R.id.et_Int_M1);
et_Int_MM = (EditText) findViewById(R.id.et_Int_MM);
et_Int_Phy = (EditText) findViewById(R.id.et_Int_Phy);
et_Int_Chem = (EditText) findViewById(R.id.et_Int_Chem);
et_Int_Cp = (EditText) findViewById(R.id.et_Int_Cp);
et_Int_ElcsLab = (EditText) findViewById(R.id.et_Int_ElcsLab);
et_Int_EpLab = (EditText) findViewById(R.id.et_Int_EpLab);
et_Int_ItLab = (EditText) findViewById(R.id.et_Int_ItLab);
et_Int_Draw = (EditText) findViewById(R.id.et_Int_Draw);
//EXTERNAL
et_Ext_Eng = (EditText) findViewById(R.id.et_Ext_Eng);
et_Ext_M1 = (EditText) findViewById(R.id.et_Ext_M1);
et_Ext_MM = (EditText) findViewById(R.id.et_Ext_MM);
et_Ext_Phy = (EditText) findViewById(R.id.et_Ext_Phy);
et_Ext_Chem = (EditText) findViewById(R.id.et_Ext_Chem);
et_Ext_Cp = (EditText) findViewById(R.id.et_Ext_Cp);
et_Ext_ElcsLab = (EditText) findViewById(R.id.et_Ext_ElcsLab);
et_Ext_EpLab = (EditText) findViewById(R.id.et_Ext_EpLab);
et_Ext_ItLab = (EditText) findViewById(R.id.et_Ext_ItLab);
et_Ext_Draw = (EditText) findViewById(R.id.et_Ext_Draw);
//INITIALISING BUTTON
btn_Cal1 = (Button) findViewById(R.id.btn_Cal1);
btn_Ok1 = (Button) findViewById(R.id.btn_Ok1);
//WHEN SAVE BUTTON IS CLICKED.
btn_Ok1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//GETTING VALUES FROM EDIT TEXT.
//INTERNALS.
IEng = getIntValue(et_Int_Eng);
IM1 = getIntValue(et_Int_M1);
IMM = getIntValue(et_Int_MM);
IEPhy = getIntValue(et_Int_Phy);
IEChem = getIntValue(et_Int_Chem);
ICp = getIntValue(et_Int_Cp);
IEDraw = getIntValue(et_Int_Draw);
IELCS_Lab = getIntValue(et_Int_ElcsLab);
IEP_LAB = getIntValue(et_Int_EpLab);
//EXTERNALS.
EEng = getIntValue(et_Ext_Eng);
EM1 = getIntValue(et_Ext_M1);
EMM = getIntValue(et_Ext_MM);
EEPhy = getIntValue(et_Ext_Phy);
EEChem = getIntValue(et_Ext_Chem);
ECp = getIntValue(et_Ext_Cp);
EEDraw = getIntValue(et_Ext_Draw);
EELCS_Lab = getIntValue(et_Ext_ElcsLab);
EEP_LAB = getIntValue(et_Ext_EpLab);
EIT_LAB = getIntValue(et_Ext_ItLab);
//CALCUATIONS.
//INTERNAL TOTAL.
ITotal1 = (IEng+IM1+IMM+IEPhy+IEChem+ICp+IEDraw+IELCS_Lab+IEP_LAB+IIT_LAB);
//EXTERNAL TOTAL.
ETotal1 = (EEng+EM1+EMM+EEPhy+EEChem+ECp+EEDraw+EELCS_Lab+EEP_LAB+EIT_LAB);
//TOTAL.
Total1 = (ITotal1+ETotal1);
//PERCENTAGE.
Percentage1 = (float)(Total1/10);
f1 = Float.toString(Percentage1);
//CREATING TOAST.
Toast.makeText(getBaseContext(),"Press Result",Toast.LENGTH_SHORT).show();
}
});
btn_Cal1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(FirstMarks.this,FirstResult.class);
Bundle b = new Bundle();
b.putInt("res1",Total1);
b.putString("per1",f1);
i.putExtras(b);
startActivity(i);
finish();
}
});
}
//SUB-FUNCTION FOR GETTING INTEGER FROM EDITTEXT.
private int getIntValue(EditText et) throws NumberFormatException {
int i =0;
String s;
try {
s = et.getText().toString();
if(s.equals("")){
Toast.makeText(getApplicationContext(),"Invalid Marks",Toast.LENGTH_SHORT).show();
}
i = Integer.parseInt(s);
return i;
} catch (NumberFormatException e) {
Log.e("ERROR:", "NOT A NUMBER");
}
return 0;
}
}
**SECONDACTIVITY**
package com.jntuhcalculator.anu.jntuhcalculator;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
/**
* Created by anu on 19/9/15.
*/
public class SecondMarks_1 extends Activity {
TextView tv_PS,tv_MFCS,tv_DS,tv_DLD,tv_EDC,tv_BEE,tv_EELab,tv_DSLab;
TextView tv_Subjects21, tv_Internal21, tv_External21;
EditText et_Int_PS, et_Int_MFCS, et_Int_DS, et_Int_DLD, et_Int_EDC, et_Int_BEE, et_Int_EELab, et_Int_DSLab;
EditText et_Ext_PS, et_Ext_MFCS, et_Ext_DS, et_Ext_DLD, et_Ext_EDC, et_Ext_BEE, et_Ext_EELab, et_Ext_DSLab;
Button btn_Cal21, btn_Ok21;
int IPS,IMFCS,IDS,IDLD,IEDC,IBEE,IEE_Lab,IDS_Lab;
int EPS,EMFCS,EDS,EDLD,EEDC,EBEE,EEE_Lab,EDS_Lab;
int ITotal21,ETotal21,Total21;
float Percentage21;
String f21;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondmarks_1);
//INITIALISING VIEWS.
//INITIALISING TEXT VIEWS.
tv_Subjects21 = (TextView) findViewById(R.id.tv_Subject21);
tv_Internal21 = (TextView) findViewById(R.id.tv_Internal21);
tv_External21 = (TextView) findViewById(R.id.tv_External21);
//SUBJECT TEXT VIEWS.
tv_PS = (TextView) findViewById((R.id.tv_PS));
tv_MFCS = (TextView) findViewById((R.id.tv_MFCS));
tv_DS = (TextView) findViewById((R.id.tv_DS));
tv_DLD = (TextView) findViewById((R.id.tv_DLD));
tv_EDC = (TextView) findViewById((R.id.tv_EDC));
tv_BEE = (TextView) findViewById((R.id.tv_BEE));
tv_EELab = (TextView) findViewById((R.id.tv_EE_Lab));
tv_DSLab = (TextView) findViewById((R.id.tv_DS_Lab));
//INITIALISING EDIT TEXT.
//INTERNAL
et_Int_PS = (EditText) findViewById(R.id.et_Int_PS);
et_Int_MFCS = (EditText) findViewById(R.id.et_Int_MFCS);
et_Int_DS = (EditText) findViewById(R.id.et_Int_DS);
et_Int_DLD = (EditText) findViewById(R.id.et_Int_DLD);
et_Int_EDC = (EditText) findViewById(R.id.et_Int_EDC);
et_Int_BEE = (EditText) findViewById(R.id.et_Int_BEE);
et_Int_EELab = (EditText) findViewById(R.id.et_Int_EELab);
et_Int_DSLab = (EditText) findViewById(R.id.et_Int_DSLab);
//EXTERNAL
et_Ext_PS = (EditText) findViewById(R.id.et_Ext_PS);
et_Ext_MFCS = (EditText) findViewById(R.id.et_Ext_MFCS);
et_Ext_DS = (EditText) findViewById(R.id.et_Ext_DS);
et_Ext_DLD = (EditText) findViewById(R.id.et_Ext_DLD);
et_Ext_EDC = (EditText) findViewById(R.id.et_Ext_EDC);
et_Ext_BEE = (EditText) findViewById(R.id.et_Ext_BEE);
et_Ext_EELab = (EditText) findViewById(R.id.et_Ext_EELab);
et_Ext_DSLab = (EditText) findViewById(R.id.et_Ext_DSLab);
//INITIALISING BUTTON
btn_Cal21 = (Button) findViewById(R.id.btn_Cal21);
btn_Ok21 = (Button) findViewById(R.id.btn_Ok21);
//DISPLAYING SUBJECT NAMES WHEN TEXT VIEW IS CLICKED.
tv_PS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
disp(tv_PS, "PS:Probabilty & Statistics");
}
});
tv_MFCS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
disp(tv_MFCS, "MFCS:Mathematical Foundation Of Computer Science");
}
});
tv_DS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {disp(tv_DS, "DS:Data Structures");
}
});
tv_DLD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
disp(tv_DLD, "DLD:Digital Logic Design");
}
});
tv_EDC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
disp(tv_EDC, "EDC:Electronic Devices & Circuits");
}
});
tv_BEE.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { disp(tv_BEE, "BEE:Basic Electrical Engineering");
}
});
tv_EELab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { disp(tv_EELab, "Electrical & Electronics Lab");
}
});
tv_DSLab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {disp(tv_DSLab, "Data Structures Lab");
}
});
//WHEN SAVE BUTTON IS CLICKED.
btn_Ok21.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//GETTING VALUES FROM EDIT TEXT.
//INTERNALS.
IPS = getIntValue(et_Int_PS);
IMFCS = getIntValue(et_Int_MFCS);
IDS = getIntValue(et_Int_DS);
IDLD = getIntValue(et_Int_DLD);
IEDC = getIntValue(et_Int_EDC);
IBEE = getIntValue(et_Int_BEE);
IEE_Lab = getIntValue(et_Int_EELab);
IDS_Lab = getIntValue(et_Int_DSLab);
//EXTERNALS.
EPS = getIntValue(et_Ext_PS);
EMFCS = getIntValue(et_Ext_MFCS);
EDS = getIntValue(et_Ext_DS);
EDLD = getIntValue(et_Ext_DLD);
EEDC = getIntValue(et_Ext_EDC);
EBEE = getIntValue(et_Ext_BEE);
EEE_Lab = getIntValue(et_Ext_EELab);
EDS_Lab = getIntValue(et_Ext_DSLab);
//CALCULATIONS.
//INTERNAL TOTAL.
ITotal21 = (IPS+IMFCS+IDS+IDLD+IEDC+IBEE+IEE_Lab+IDS_Lab);
//EXTERNAL TOTAL.
ETotal21 = (EPS+EMFCS+EDS+EDLD+EEDC+EBEE+EEE_Lab+EDS_Lab);
//TOTAL.
Total21 = (ITotal21+ETotal21);
//PERCENTAGE.
Percentage21 = ((Total21/750)*100);
f21 = Float.toString(Percentage21);
//CREATING TOAST.
Toast.makeText(getBaseContext(),"Press Result",Toast.LENGTH_SHORT).show();
}
});
btn_Cal21.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(SecondMarks_1.this,FirstResult.class);
Bundle b = new Bundle();
b.putInt("res1",Total21);
b.putString("per1",f21);
i.putExtras(b);
startActivity(i);
finish();
}
});
}
//SUB-FUNCTION FOR GETTING INTEGER FROM EDITTEXT.
private int getIntValue(EditText et) throws NumberFormatException {
int i =0;
String s;
try {
s = et.getText().toString();
if(s.equals("")){
Toast.makeText(getApplicationContext(),"Invalid Marks",Toast.LENGTH_SHORT).show();
}
i = Integer.parseInt(s);
return i;
} catch (NumberFormatException e) {
Log.e("ERROR:", "NOT A NUMBER");
}
return 0;
}
private void disp(TextView tv,String s){
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
}
**RESULTACTIVITY**
<pre><code>
package com.jntuhcalculator.anu.jntuhcalculator;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
/**
* Created by anu on 18/9/15.
*/
public class FirstResult extends Activity {
EditText et_Total1,et_Percentage1;
Button btn_Exit1;
int sres1;
String sper1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_first);
//INITIALISING VIEWS.
et_Total1 = (EditText) findViewById(R.id.et_Total1);
et_Percentage1 = (EditText) findViewById(R.id.et_Percentage1);
btn_Exit1 = (Button) findViewById(R.id.btn_Exit1);
//GETTING DATA FROM PREVIOUS ACTIVITY.
Bundle b = getIntent().getExtras();
sres1 = b.getInt("res1", 0);
sper1 = b.getString("per1");
//Converting Float Into String.
//f = Float.toString(sper1);
//SETTING RESULTS.
et_Total1.setText(sres1+"");
et_Percentage1.setText(sper1+"%");
//WHEN EXIT IS CLICKED.
btn_Exit1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getBaseContext(), YearDetails.class);
i.putExtra("Total",sres1);
startActivity(i);
finish();
System.exit(0);
}
});
}
}
You are properly not able to send values between different activities, i will give you an example, try it.
The syntax is like this
For sending data
String data = getIntent().getExtras().getString("keyName");
Intent intent = new Intent(ActivityOne.this, ActivityTwo.class);
intent.putExtra("keyName","value");
For receiving at ActivityTwo
String value= getIntent().getStringExtra("keyName");
Intent intent = getIntent();
Bundle extras = intent.getExtras();
Additional hint:-
So you need to edit in FirstActivity
btn_Cal21.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(SecondMarks_1.this,FirstResult.class);
Bundle b = new Bundle();
b.putInt("res1",Total21);
b.putString("per1",f21);
i.putExtras(b);
startActivity(i);
finish();
}
});
Same for the following activities.
Still Did not get ? Actually in you FirstActivity you have put
Intent i = new Intent(FirstMarks.this,FirstResult.class);
Bundle b = new Bundle();
b.putInt("res1",Total1);
b.putString("per1",f1);
And in your second activity.
Intent i = new Intent(SecondMarks_1.this,FirstResult.class);
Bundle b = new Bundle();
b.putInt("res1",Total21);
b.putString("per1",f21);
i.putExtras(b);
startActivity(i);
You see you have used per1 string in both places, change that, that is probably causing the app not to get values(possibly give some other string).
And in this part, you need to add code for 2nd activity result to be received.
Bundle b = getIntent().getExtras();
sres1 = b.getInt("res1", 0);
sper1 = b.getString("per1");
Hope that helps.
I have an app, which consists of a tabhost. I am using a AsyncTask to perform some internet work in the background. Now in the onPostExecute, I want it to start a new activity. When I create a new intent, the new activity is shown, but there are no tabs.. it's just the activity.
Now i've read online how to do this, And i've managed to get into the right direction i think. This is the entire code:
package com.appsoweb.kvodeventer;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ActivityGroup;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class KVOMeldingen extends ActivityGroup {
public static final JSONObject jsonResult = null;
Button bLogin, bCreateAccount, bResetPassword;
EditText etUsername, etPassword;
static String Username;
static String Password;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.meldingen);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
Button bLogin = (Button) findViewById(R.id.bLogin);
Button bCreateAccount = (Button) findViewById(R.id.bCreateAccount);
Button bResetPassword = (Button) findViewById(R.id.bResetPassword);
bLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (etUsername.length() <= 0) {
etUsername.setError("Veld mag niet leeg zijn");
} else if (etPassword.length() <= 0) {
etPassword.setError("Veld mag niet leeg zijn");
} else {
Username = etUsername.getText().toString();
Password = etPassword.getText().toString();
}
LoginTask NDLT = new LoginTask();
NDLT.execute();
}
});
bCreateAccount.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Doe iets hier.......
}
});
bResetPassword.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Doe iets hier........
}
});
}
public static String getUsername() {
return Username;
}
public static String getPassword() {
return Password;
}
class LoginTask extends AsyncTask<Void, Void, JSONObject> {
ProgressDialog waitingDialog;
#Override
protected void onPreExecute() {
waitingDialog = new ProgressDialog(KVOMeldingen.this);
waitingDialog.setMessage("Laden...");
waitingDialog.show();
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(Void... params) {
JSONObject json = JsonFunctionLogin
.getJsonLoginResult("http://api.crossalertdeventer.nl/login.json");
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
super.onPostExecute(json);
if (waitingDialog.isShowing()) {
waitingDialog.dismiss();
Log.d("iets gebeurt", "gedaan");
}
try {
String LoginResult = json.getString("login");
String UserIdResult = json.getString("user_id");
Log.d("LoginResult", LoginResult);
Log.d("LoginUserId", UserIdResult);
json = null;
Intent intent = new Intent(KVOMeldingen.this, KVOCards.class);
View view = getLocalActivityManager().startActivity("KVOCards", intent
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
replaceView(view);
} catch (Exception e) {
Log.e("KVOMeldingen", "error" + e.getMessage());
}
}
public void replaceView(View v){
setContentView(v);
}
}
}
As you can see: I've created a View that will be shown trough an Intent. But the intent doesn't launch after the onbackground. It gives me an error:
Unable to start Activity componentInfo Unable to add window ... Token..... is not valid... Is your application running?
What am i doing wrong?
Thnx in advance
Starting a new Activity means you are navigating from your TabActivity to a normal Activity. Obviously you can't find a tab in Activity. You have to replace views instead of creating Activities.
Here is a good example of how to use ActivityGroup with TabActivity.
http://web.archive.org/web/20100816175634/http://blog.henriklarsentoft.com/2010/07/android-tabactivity-nested-activities/
But still this approach has been deprecated. You might have to consider using fragments though.
Take a look here, http://developer.android.com/resources/samples/Support4Demos/src/com/example/android/supportv4/app/FragmentTabs.html
I tried to make a signup page in android where I use a reset button that should clear all fields in the page. Please see the code below and correct it as my code is not working.
Button btnreset = (Button) findViewById(R.id.btnreset);
btnreset.setOnClickListener(new View.OnClickListener() {
public void restartActivity(Activity act){
Intent intent=new Intent();
act.finish();
intent.setClass(act, act.getClass());
act.startActivity(intent);
}
}
this is an signup page and fields are first name,last name,user id,password.when user click on reset button it clear all the fields who's filled the user.I'm give a complete source code to you please check this:
package com.boyzcorn.android.fyp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.content.Intent;
public class signup extends Activity{
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.signup);
Button b = (Button) findViewById(R.id.btnClick2);
Button btnreset = (Button) findViewById(R.id.btnreset);
final EditText eText1 = (EditText)findViewById(R.id.firstname);
final EditText eText2 = (EditText)findViewById(R.id.lastname);
final EditText eText3 = (EditText)findViewById(R.id.userid);
final EditText eText4 = (EditText)findViewById(R.id.password);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
{
if(eText1.getText().toString().equals("") ||eText2.getText().toString().equals("") || eText3.getText().toString().equals("") ||eText4.getText().toString().equals(""))
{
Toast.makeText( getApplicationContext(),"Fill Empty Fields",Toast.LENGTH_SHORT ).show();
}
else
{
Intent i = new Intent(signup.this,login.class);
startActivity(i);
}
}
}
});
}
btnreset.setOnClickListener(new View.OnClickListener() {
public void restartActivity(Activity act){
Intent intent=new Intent();
act.finish();
intent.setClass(act, act.getClass());
act.startActivity(intent);
}
}
public void onClick(View arg0) {
}
}
You've only defined the function; you're not calling it. You will need to execute restartActivity(signup.this) from the OnClickListener.
Also, your intent will likely not execute, because its parent has been finished. Perhaps rearranging the lines of code might help, but a better solution would be having the parent activity start it. Try replacing the click listener with:
btnreset.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Activity act = signup.this;
Intent intent = new Intent(act, act.getClass());
act.startActivity(intent);
act.finish();
}
}