i have made program which works with AsyncTask it prints a list of the JSON data when program is executed, but the problem is that i want it to execute when i press the button. How do i get the results of AsyncTask into my onClickButtonListener ? How do i call AsyncTask from onClick?
Code:
public class Instillinger extends MainActivity {
DatabaseHelper myDb;
String navn;
String adresse;
String bilmere;
TextView visNavn;
TextView visAdresse;
TextView visBil;
EditText navnFelt;
EditText adrFelt;
EditText bilFelt;
Button lagreButton;
Button tilbakeButton;
Button visDataButton;
List<Bruker> brukere;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.instillinger);
myDb = new DatabaseHelper(this);
// visNavn = (TextView) findViewById(R.id.visNavn);
visAdresse = (TextView) findViewById(R.id.visAdresse);
//visBil = (TextView) findViewById(R.id.visBil);
navnFelt = (EditText) findViewById(R.id.navnFelt);
adrFelt = (EditText) findViewById(R.id.adrFelt);
bilFelt = (EditText) findViewById(R.id.bilFelt);
lagreButton = (Button) findViewById(R.id.lagreButton);
tilbakeButton = (Button) findViewById(R.id.tilbakeButton);
//visDataButton = (Button) findViewById(R.id.visData);
brukere = myDb.getBrukere();
for(Bruker b: brukere){
String log = "Du er registrert som: "+ b.getNavn() + "\n" +
"Adresse: " + b.getAdresse() + "\n" +
"Bilmerke: " + b.getBilmerke() + "\n" +
"For å oppdatere informasjon fyll Alle feltene nede";
visAdresse.setText(log);
}
settInnData();
}
public void settInnData() {
lagreButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myDb.addContact(new Bruker("Giedrius","mldc","123","1"));
brukere = myDb.getBrukere();
for(Bruker b: brukere){
String log = "Du er registrert som: "+ b.getNavn() + "\n" +
"Adresse: " + b.getAdresse() + "\n" +
"Bilmerke: " + b.getBilmerke() + "\n" +
"Bilmerke: " + b.getState() + "\n" +
"For å oppdatere informasjon fyll Alle feltene nede";
visAdresse.setText(log);
}
//myDb.getContact(myDb.getCount()).toString();
}
});
}
}}
You can call your AsyncTask class inside your button listener by simply invoking new YourAsyncTaskName().execute(). Good Luck.
Related
I am trying to build a quiz app, where admin will create questions in admin activity and these questions will be shown as quiz exam in another activity. While I try to fill up the form by clicking CREATE QUESTION button from admin activity my app is going back to previous activity(adminlogin activity)
Here is the code of AdminActivity:
public class AdminActivity extends AppCompatActivity {
Button btnCreateQuestion, btnReadQuestion, btnDeleteQuestion;
EditText editTextQuestion, editTextOption1, editTextOption2, editTextOption3, editTextOption4,
editTextAnswerNo,editTextChapterNo;
QuizDbHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin);
btnCreateQuestion = findViewById(R.id.btnCreateQuestion);
btnReadQuestion = findViewById(R.id.btnReadQuestions);
btnDeleteQuestion = findViewById(R.id.btnDeleteQuestions);
editTextQuestion = findViewById(R.id.editTextQuestion);
editTextOption1 = findViewById(R.id.editTextOption1);
editTextOption2 = findViewById(R.id.editTextOption2);
editTextOption3 = findViewById(R.id.editTextOption3);
editTextOption4 = findViewById(R.id.editTextOption4);
editTextAnswerNo = findViewById(R.id.editTextAnswerNo);
editTextChapterNo = findViewById(R.id.editTextChapterNo);
db = new QuizDbHelper(this);
btnCreateQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String question = editTextQuestion.getText().toString();
String option1 = editTextOption1.getText().toString();
String option2 = editTextOption2.getText().toString();
String option3 = editTextOption3.getText().toString();
String option4 = editTextOption4.getText().toString();
Integer answerNo = Integer.parseInt(editTextAnswerNo.getText().toString());
String chapterName = editTextAnswerNo.getText().toString();
if( question != "" && option1 != "" && option2 != "" && option3 != "" && option4 != "" && answerNo!= null && chapterName != ""){
Question q = new Question(question,option1,option2,option3,option4,answerNo,chapterName);
db.addQuestion(q);
Toast.makeText(AdminActivity.this,"Question Added", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(AdminActivity.this,"Please fill up", Toast.LENGTH_SHORT).show();
}
}
});
btnReadQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<Question> allQuestions = db.getAllQuestions();
if(allQuestions.size()< 1){
Toast.makeText(AdminActivity.this,"No questions in the Database", Toast.LENGTH_SHORT).show();
}else {
StringBuffer buffer = new StringBuffer();
for (Question q: allQuestions) {
buffer.append("Question : " + q.getQuestion() + "\n" );
buffer.append("Option1: " + q.getOption1() + "\n");
buffer.append("Option2: " + q.getOption2() + "\n");
buffer.append("Option3: " + q.getOption3() + "\n");
buffer.append("Option4: " + q.getOption4() + "\n");
buffer.append("Answer No: " + q.getAnswerNo() + "\n");
buffer.append("Option4: " + q.getChapterName() + "\n\n");
}
AlertDialog.Builder builder = new AlertDialog.Builder(AdminActivity.this);
builder.setCancelable(true);
builder.setTitle("Questions");
builder.setMessage(buffer.toString());
builder.show();
}
}
});
btnDeleteQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}}
Any clue? Thank You in Advance.
Check in onCreate function of your Activity class, did you have initialize your EditText and Button.
Also, You have to make change in your condition as below:
if(!question.equalsIgnoreCase("") && !option1.equalsIgnoreCase("") && !option2.equalsIgnoreCase("") && !option3.equalsIgnoreCase("") && !option4.equalsIgnoreCase("") && answerNo != 0 && !chapterName.equalsIgnoreCase("")
Because, == tests for reference equality (whether they are the same object).
Whereas, equalsIgnoreCase() ignores the case while comparing two strings.
Hello I just wanna ask about this code, the problem is I just want to show the getData in an EditTextview. But it only shows in a toast what do you think will be thre revisions needed for my code to call the data in getData into a EditText thank you so much for the help.
package com.example.serviceapplication;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
public class Timeinsms extends AppCompatActivity {
DatabaseHelper myDb;
EditText editTextId,editTextsmsi;
Button btngetData,btnView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timeinsms);
myDb = new DatabaseHelper(this);
editTextId = (EditText) findViewById(R.id.editText_idin);
btngetData = (Button) findViewById(R.id.button_view);
btnView = (Button) findViewById(R.id.button_viewALL);
getData();
viewAll();
}
public void getData() {
btngetData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String id = editTextId.getText().toString();
if (id.equals(String.valueOf(""))) {
editTextId.setError("Enter id to get data");
return;
}
Cursor res = myDb.getData(id);
String data = null;
if (res.moveToFirst()) {
data =
"Id:" + res.getString(0) + "\n\n" +
"Time In :" + res.getString(1) + "\n\n" +
"Customer :" + res.getString(2) + "\n\n"+
"Branch :" + res.getString(3) + "\n\n"+
"Machine :" + res.getString(4) + "\n\n";
}
showMessage("TIME OUT FORM"+"\n\n", data);
}
});
}
public void viewAll(){
btnView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res=myDb.getAllData();
if(res.getCount() == 0) {
showMessage("Error","Nothing found");
return;
}
StringBuffer buffer=new StringBuffer();
while(res.moveToNext()){
buffer.append("Id:"+res.getString(0)+"\n\n");
buffer.append("Time :"+ res.getString(1)+"\n\n");
buffer.append("Customer :"+ res.getString(2)+"\n\n");
buffer.append("Branch :"+ res.getString(3)+"\n\n");
buffer.append("Machine :"+ res.getString(4)+"\n\n\n");
}
showMessage("Time In History",buffer.toString());
}
});
}
private void showMessage(String title, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.create();
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
}
You are not showing it in a Toast, you are using an Alertdialog to Show your Message.
This would be a Toast
Toast.makeText(this,"MESSAGE TO SHOW",Toast.LENGTH_LONG).show();
At this Position
data = "Id:" + res.getString(0) + "\n\n" +
"Time In :" + res.getString(1) + "\n\n" +
"Customer :" + res.getString(2) + "\n\n"+
"Branch :" + res.getString(3) + "\n\n"+
"Machine :" + res.getString(4) + "\n\n";
you are already creating a String which contains all your data, you only have to set your Edittext with this String.
editTextId.setText("TIME OUT FORM"+"\n\n"+data);
This must be placed inside the OnClick method, as data is a local variable at this method.
I am new to android coding and need help with my project :
I have a function which I call from the OnResume of the mainActivity . The function reloads the data from the database and shows it on the list view .
Now when I go to second Activity and enter new data , the data is saved when onPause of secondActivity is called . On returning to mainActivity I don't see the changes made to list view but when I click on the same item of list view and go to second Activity again on returning for the 2nd time the changes start showing and the code works properly . What could be the possible reason for function not working in the 1st attempt ?
Note : I also call the function from onCreate of main Activity
EDIT 1:
the function to call
public void fill_list() {
cursor = db.rawQuery("SELECT * FROM " + GameEntry.TABLE + " WHERE " + GameEntry.G_DIFF + " = " + diff, null);
yesitis = cursor.moveToFirst();
if (yesitis)
count = cursor.getCount();
//int count=cursor.getCount();
listv = (ListView) findViewById(R.id.listview1);
listv.setAdapter(null);
arr.clear();
for (int j = 0; j < 15; j++) {
String data;
int j2 = j + 1;
data = String.valueOf(j2);
cursor3 = db.rawQuery("SELECT * FROM " + GameEntry.TABLE + " WHERE " + GameEntry.G_DIFF + " = " + diff+" AND "+GameEntry.G_LEVEL+" = "+j, null);
if (cursor3.moveToFirst()) {
cursor3.moveToPosition(0);
int showstate = cursor3.getColumnIndex(AppContract.GameEntry.G_STATE);
String temp1 = cursor3.getString(showstate);
if (temp1.equals("notStarted")) {
} else {
int showtime = cursor3.getColumnIndex(AppContract.GameEntry.time);
String temp2 = cursor3.getString(showtime);
data = data + " " + temp1 + " " + temp2;
}
}
arr.add(data);
}
ArrayAdapter<String> arradapt = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arr) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView textView = (TextView) super.getView(position, convertView, parent);
switch (diff) {
case 1:
textView.setBackgroundColor(Color.parseColor("#83EEA4"));
break;
case 2:
textView.setBackgroundColor(Color.parseColor("#00C5F6"));
break;
case 3:
textView.setBackgroundColor(Color.parseColor("#FF416A"));
break;
}
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
return textView;
}
};
listv.setAdapter(arradapt);
listv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> av, View view, int ii, long id) {
level_select=ii;
cursor2 = db.rawQuery("SELECT * FROM " + GameEntry.TABLE + " WHERE " + GameEntry.G_DIFF + " = " + diff + " AND " + GameEntry.G_LEVEL + " = " + ii, null);
if (cursor2.moveToFirst()) {
cursor2.moveToPosition(0);
g_exist = "yes";
} else {
g_exist = "no";
}
Intent send = new Intent(ListActivity.this, GameActivity.class);
send.putExtra("level", ii);
send.putExtra("difficulty", diff);
send.putExtra("exist", g_exist);
startActivity(send);
}
});
}
onResume :
#Override
protected void onResume() {
super.onResume();
Toast.makeText(getApplicationContext(), "onResumed called", Toast.LENGTH_LONG).show();
fill_list();
}
mainActivity onCreate :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
MobileAds.initialize(this,
"ca-app-pub-6165188418561315~3404004371");
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
diff = getIntent().getExtras().getInt("difficulty");
mhelper = new appdbhelper(this);
db = mhelper.getReadableDatabase();
fill_list();
Toast.makeText(getApplicationContext(), "sqlsize =" + String.valueOf(yesitis), Toast.LENGTH_SHORT).show();
}
onPause of second activity (enterdata function updates the specified row of database ):
#Override
protected void onPause() {
super.onPause();
//Toast.makeText(getApplicationContext(), "onPause called", Toast.LENGTH_LONG).show();
timer.stop();
enterdata();
}
Thanks in advance
I can't seem to get this. I'm trying to pass two strings to a new activity but can only get one to pass. Can someone help? I would like the passed strings to say "I would like" movieName movieGroup "everyday"
public class Main22Activity extends AppCompatActivity {
String passedVar=null;
private TextView passedView= null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main22);
Bundle extras = getIntent().getExtras();
passedVar=getIntent ().getStringExtra(MainActivity.ID_EXTRA + "movieName");
passedVar2=getIntent ().getStringExtra(MainActivity.ID_EXTRA + "movieGroup");
passedView = (TextView) findViewById(R.id.textView3);
passedView.setText("I would like " + passedVar, passedVar2 + "everyday");
}
public class Main22Activity extends AppCompatActivity {
String passedVar=null;
String passedVar2=null;
private TextView passedView= null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main22);
Bundle extras = getIntent().getExtras();
passedVar=getIntent ().getStringExtra(MainActivity.ID_EXTRA +"movieName");
passedVar2=getIntent ().getStringExtra(MainActivity.ID_EXTRA + "movieGroup");
passedView = (TextView) findViewById(R.id.textView3);
passedView.setText("I would like " + passedVar + "," + passedVar2 + "everyday");
}
Notice change in
passedVar + "," + passedVar2
I have been working this quiz for a little while, however i am struggling to match the the question with the answer.
The following line and the others which are supposed to be display the answer actually display "[[ljava.lang.string;#40585b18" and slight variations.
quesAns4.setText("4) " + answers[3]) ;
i have tried changing the line now above to:
quesAns4.setText("4) " + answers[0][3]);
Obviously i want the answers to match the questions and the method above only displays 8 from array
{"3","5","8","9"}
So basically yeah for each change of question i want them to match. If the questions is "In seconds, how long does it take for a F1 car to stop when travelling at 300km/h?" the answers possible to be displayed should be 4,6,8,10 etc.
Any help/guidance would be appreciated thanks.
Full code below!
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MathsMultiplicationActivity extends Activity {
TextView quesnum;
TextView ques;
TextView anst;
TextView ans1;
TextView ans2;
TextView ans3;
TextView ans4;
ImageView cross;
ImageView tick;
Button nxt;
int qno = 1;
int right_answers = 0;
int wrong_answers = 0;
int rnd1;
int rnd2;
String [] questions = {"How much mph does the F-Duct add to the car?",
"What car part is considered the biggest performance variable?",
"What car part is designed to speed up air flow at the car rear?",
"In seconds, how long does it take for a F1 car to stop when travelling at 300km/h?",
"How many litres of air does an F1 car consume per second?",
"What car part can heavily influence oversteer and understeer?",
"A third of the cars downforce can come from what?",
"Around how much race fuel would be consumed per 100km?","The first high nose cone was introduced when?",
"An increase in what, has led to the length of exhaust pipes being shortened drastically?"};
String [] [] answers = {{"3","5","8","9"},
{"Tyres","Front Wing","F-Duct","Engine"},
{"Diffuser","Suspension","Tyres","Exhaust"},
{"4","6","8","10"},
{"650","10","75","450"},
{"Suspension","Tyres","Cockpit","Chassis"},
{"Rear Wing","Nose Cone","Chassis","Engine"},
{"75 Litres","100 Litres","50 Litres","25 Litres"},
{"1990","1989","1993","1992"},
{"Engine RPM","Nose Cone Lengths","Tyre Size","Number of Races"}};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.multiplechoice);
// Importing all assets like buttons, text fields
quesnum = (TextView) findViewById(R.id.questionNum);
ques = (TextView) findViewById(R.id.question);
anst = (TextView) findViewById(R.id.answertit);
ans1 = (TextView) findViewById(R.id.answer1);
ans2 = (TextView) findViewById(R.id.answer2);
ans3 = (TextView) findViewById(R.id.answer3);
ans4 = (TextView) findViewById(R.id.answer4);
nxt = (Button) findViewById(R.id.btnNext);
cross = (ImageView) findViewById(R.id.cross);
tick = (ImageView) findViewById(R.id.tick);
cross.setVisibility(View.GONE);
tick.setVisibility(View.GONE);
quesnum.setText("Question: " + qno + "/10");
final Button buttonAbout = (Button) findViewById(R.id.btnNext);
buttonAbout.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
next();
}
private void next() {
qno++;
change_question();
}
private void change_question() {
if(tick.getVisibility() == View.VISIBLE){
right_answers++;
}
if(cross.getVisibility() == View.VISIBLE){
wrong_answers++;
}
if(qno==questions.length){
}else{
cross.setVisibility(View.GONE);
tick.setVisibility(View.GONE);
rnd1 = (int)Math.ceil(Math.random()*3);
rnd2 = (int)Math.ceil(Math.random()*questions.length)-1;
ques.setText(questions[rnd2]);
if(questions[rnd2]=="x")
{
change_question();
}
}
questions[rnd2]="x";
if(rnd1==1){
TextView quesAns1 = (TextView) findViewById(R.id.answer1);
quesAns1.setText("1) " + answers[0]) ;
TextView quesAns2 = (TextView) findViewById(R.id.answer2);
quesAns2.setText("2) " + answers[1]) ;
TextView quesAns3 = (TextView) findViewById(R.id.answer3);
quesAns3.setText("3) " + answers[2]) ;
TextView quesAns4 = (TextView) findViewById(R.id.answer4);
quesAns4.setText("4) " + answers[3]) ;
}
if(rnd1==2){
TextView quesAns1 = (TextView) findViewById(R.id.answer1);
quesAns1.setText("1) " + answers[2]) ;
TextView quesAns2 = (TextView) findViewById(R.id.answer2);
quesAns2.setText("2) " + answers[0]) ;
TextView quesAns3 = (TextView) findViewById(R.id.answer3);
quesAns3.setText("3) " + answers[1]) ;
TextView quesAns4 = (TextView) findViewById(R.id.answer4);
quesAns4.setText("4) " + answers[3]) ;
}
if(rnd1==3){
TextView quesAns1 = (TextView) findViewById(R.id.answer1);
quesAns1.setText("1) " + answers[1]) ;
TextView quesAns2 = (TextView) findViewById(R.id.answer2);
quesAns2.setText("2) " + answers[2]) ;
TextView quesAns3 = (TextView) findViewById(R.id.answer3);
quesAns3.setText("3) " + answers[0]) ;
TextView quesAns4 = (TextView) findViewById(R.id.answer4);
quesAns4.setText("4) " + answers[3]) ;
}
}
});
//Answer 1 click functions
ans1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
ans1Action();
}
private void ans1Action() {
//enable_disable(0);
if(rnd1==1){
tick.setVisibility(View.VISIBLE);
}else{
cross.setVisibility(View.VISIBLE);
}
}
});
//Answer 2 click functions
ans2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
ans2Action();
}
private void ans2Action() {
//enable_disable(0);
if(rnd1==2){
tick.setVisibility(View.VISIBLE);
}else{
cross.setVisibility(View.VISIBLE);
}
}
});
//Answer 3 click functions
ans3.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
ans3Action();
}
private void ans3Action() {
//enable_disable(0);
if(rnd1==3){
tick.setVisibility(View.VISIBLE);
}else{
cross.setVisibility(View.VISIBLE);
}
}
});
//Answer 4 click functions
ans4.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
ans4Action();
}
private void ans4Action() {
//enable_disable(0);
if(rnd1==4){
tick.setVisibility(View.VISIBLE);
}else{
cross.setVisibility(View.VISIBLE);
}
}
});
}
}
This :
quesAns4.setText("4) " + answers[0][3]);
Works if this is the 1st question.
What you should do is to have in the change_question function the number of the question in parameter change_question(int questionNumber)
Then, when you set the texts, you use :
quesAns4.setText("4) " + answers[questionNumber][3]);
If your questions start at 0.
Else, you use :
quesAns4.setText("1) " + answers[questionNumber-1][0]);
quesAns4.setText("2) " + answers[questionNumber-1][1]);
quesAns4.setText("3) " + answers[questionNumber-1][2]);
quesAns4.setText("4) " + answers[questionNumber-1][3]);
To print arrays in a user-friendly manner, you need to loop over the array items or you can use the Arrays.deepToString method:
String yourPrinterFriendlyArray = Arrays.deepToString(answers[0]);
quesAns4.setText("4) " + yourPrinterFriendlyArray);