unable to search database from button.setOnClick .getText as String becomes null - java

I am making android app that takes user input from EditText on press of button from button.setOnClick() and use the string.getText() to search the database. But the string becomes null and no way i can send it
DbBackend.class where the search function is.
I checked and database works fine on static query which you can set to = "xyz" but no way i am able to use the user input to query the database.
Here is my code: MainActivity.java
package com.vadhod.dictcopy;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.sql.Array;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import static android.app.PendingIntent.getActivity;
public class MainActivity extends AppCompatActivity {
TextView textView;
EditText searchBar;
Button searchButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final DbBackend dbBackend = new DbBackend(MainActivity.this);
searchBar = (EditText) findViewById(R.id.searchBar);
searchButton = (Button) findViewById(R.id.searchButton);
textView = (TextView)findViewById(R.id.textView);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
String input = searchBar.getText().toString();
ArrayList<String> terms = dbBackend.getList(input);
StringBuilder builder = new StringBuilder();
for (String details : terms) {
builder.append(details + "\n");
}
textView.setText(builder.toString());
}catch (Exception e){
e.printStackTrace();
}
}
});
}
}
DbBackend.java
package com.vadhod.dictcopy;
import ...
public class DbBackend extends DatabaseObject {
public DbBackend(Context context){
super(context);
}
public ArrayList<String> getList(String search){
ArrayList<String> kWords = new ArrayList<String>();
String searchQuery = "SELECT kName FROM dictionary WHERE eName LIKE '%" + search + "%'";
try {
Cursor kCursor = this.getDbConnection().rawQuery(searchQuery, null);
if (kCursor != null){
kCursor.moveToFirst();
for (int i = 0; i < kCursor.getCount(); i++ ){
String sword = kCursor.getString(kCursor.getColumnIndexOrThrow("kName"));
kWords.add(sword);
kCursor.moveToNext();
}
kCursor.close();
return kWords;
}
return kWords;
}catch (Exception e){
e.printStackTrace();
}
return kWords;
}
}
Any help please on how to use the string when user press the search button and search that through the database and return the query?
Updated the moved code

Assuming that inside the searchButton.setOnClickListener(new View.OnClickListener() {...}); the search is working, and outside - not. The problem is your
//Option 1 not working
ArrayList<String> terms2 = dbBackend2.getList(input);
is called during the Activity setup before any view is shown to the user. So, the input is not filled at that time. You have to move this code into an onclick listener, like you did in the code above these lines.
Or provide some other source for the input.
Upd:
For the NullPointer: in your layout file activity_main you need to have a TextView with id textView. Because you do the following:
// find the textview in the layout
textView = (TextView)findViewById(R.id.textView);
// do the search, get results
...
// set textview's text, at this moment textView must not be null
textView.setText(kbuilder.toString());

Related

Backendless fetch all data from database but returning one result

I set up a database in Backendless and started running it on Android Studio. The app is able to access the database and the connection is stable. But when I run the app, it only returns one result from the database. Is it possible to loop through all the items in the database? I built the app using this tutorial: https://www.youtube.com/watch?v=KeYC6gJyt-k&t=1524s&ab_channel=JohanJurrius Here is my code.
package com.mbass.examples;
import android.app.Activity;
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;
import com.backendless.Backendless;
import com.backendless.IDataStore;
import com.backendless.async.callback.AsyncCallback;
import com.backendless.exceptions.BackendlessFault;
import com.backendless.persistence.DataQueryBuilder;
import java.util.List;
import java.util.Map;
public class MainActivity extends Activity {
private TextView status;
private TextView listtext;
private Button updateButton;
List<VIdeos> videos;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
Backendless.setUrl(Defaults.SERVER_URL);
Backendless.initApp(getApplicationContext(), Defaults.APPLICATION_ID, Defaults.API_KEY);
status = (TextView) findViewById(R.id.status);
updateButton = (Button) findViewById(R.id.update_button);
updateButton.setEnabled(false);
final int[] textViews = {R.id.textView1, R.id.textView2, R.id.textView3};
String whereClause = "name != 'Bill'";
DataQueryBuilder queryBuilder = DataQueryBuilder.create();
queryBuilder.setWhereClause(whereClause);
queryBuilder.setPageSize(10).setOffset(0);
queryBuilder.setSortBy("name");
Backendless.Persistence.of(VIdeos.class).find(queryBuilder, new AsyncCallback<List<VIdeos>>() {
#Override
public void handleResponse(List<VIdeos> response) {
for (int i = 0; i < response.size(); i++) {
Toast.makeText(MainActivity.this, "Name: " + response.get(i).getName() + "\n" +
"ID: " + response.get(i).getCreated(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void handleFault(BackendlessFault fault) {
Toast.makeText(MainActivity.this, fault.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
What happens when you comment out this line?
queryBuilder.setWhereClause(whereClause);
Your code sets the page size to 10 objects with the following line of code:
queryBuilder.setPageSize(10).setOffset(0)
The response is an array containing 10 objects. If you need more objects, change the page size. The maximum page size is 100

Trying to add to an arraylist on a different activity each time a button is pressed

So just to practice I've created a Pythagorean theorem calculator app. I want each answer that I obtain to be stored in another activity(a "history" page). I'm trying to use intents to send/receive the arraylist and items. I get the most recent one, but it is overwritten after each press of the button.
package com.example.hypnotenusecalculatorrebuild;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
//ToDo history button is broken. doesn't display listview when pressed.
public void toHistory(View view) {
// Intent intent = new Intent(getApplicationContext(), HistoryActivity.class);
//
// startActivity(intent);
}
public void findHypno(View view) {
Log.i("Info", "button pressed");
EditText editTextNumberA = (EditText) findViewById(R.id.editTextNumberA);
EditText editTextNumberB = (EditText) findViewById(R.id.editTextNumberB);
TextView textViewAnswer = (TextView) findViewById(R.id.textViewAnswer);
String message;
String cSquared;
if (editTextNumberA.getText().toString().isEmpty() || editTextNumberB.getText().toString().isEmpty()) {
message = "Please enter a number for each dimension";
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
} else {
Number numberA = new Number();
Number numberB = new Number();
Number numberC = new Number();
numberA.number = Double.parseDouble(editTextNumberA.getText().toString());
numberB.number = Double.parseDouble(editTextNumberB.getText().toString());
numberA.squareNumber();
numberB.squareNumber();
numberC.number = numberA.number + numberB.number;
numberC.squareRoot();
Log.i("test numberA", String.valueOf(numberA.number));
Log.i("test numberB", String.valueOf(numberB.number));
Log.i("test numberC", String.valueOf(numberC.number));
cSquared = Double.toString(numberC.number);
textViewAnswer.setText(cSquared);
ArrayList<String> historyList = new ArrayList<String>();
historyList.add("test");
Intent intent = new Intent(getApplicationContext(), HistoryActivity.class);
intent.putExtra("answer", cSquared);
intent.putStringArrayListExtra("arrayList", historyList);
startActivity(intent);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
package com.example.hypnotenusecalculatorrebuild;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import java.util.function.ToDoubleBiFunction;
public class HistoryActivity extends AppCompatActivity {
public void back(View view) {
finish();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
Intent getList = getIntent();
ArrayList<String> historyList = getList.getStringArrayListExtra("arrayList");
historyList.add(getList.getStringExtra("answer"));
ListView listViewHistory = (ListView) findViewById(R.id.listViewHistory);
ArrayAdapter historyListArrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, historyList);
listViewHistory.setAdapter(historyListArrayAdapter);
// ToDo - intent isn't working as attended, only saves one item and gets overwritten each time
//Intent historyIntent = getIntent();
// get extra needs a name from put extra
// String testGetIntent = historyIntent.getStringExtra("answer");
// Log.i("testIntentString", testGetIntent);
// historyList.add(historyIntent.getStringExtra("answer"));
}
}
here is a different approach. make a public interface in a separate file named "extensions" or whatever and initialize your arraylist there like so:
public interface ext {
ArrayList<String> myArray = new ArrayList<String>();
}
this interface is created when the app runs and lives for as long as the app lives meaning you can always access and manipulate it anywhere in your app without worrying whether the activity is being killed or not. so you can add or remove elements to or from it wherever you want.
Access the array this way:
ext.myArray.add("new item")

Further guidance with a Spinner

after testing out examples given here and here, I thought I would be able to add a score-point if the user selected the correct drop-down item. (I'm making a simple quiz app that toasts the final score).
Obviously this is too advanced for me, but I really don't want to give up and wondered if anyone might have any idea as to what I'm doing wrong please?
Here is how I have it set out in the MainActivity.java, with my failed attempts of implementing a way of checking the selected item stripped out:
First I set out the questions:
package com.example.android.arabic;
import android.content.Intent;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.os.Bundle;
import android.util.Log;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.view.View.OnClickListener;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import com.example.android.arabic.Nature.Nature;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements OnItemSelectedListener{
int arabicScore = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// add emoji Q1
TextView q1 = findViewById(R.id.Q1_question);
q1.setText(Nature.HONEY_BEE);
// add emoji A2_option1
TextView qa2Option1 = findViewById(R.id.A2_option1);
qa2Option1.setText(Nature.GOAT);
// add emoji A2_option2
TextView qa2Option2 = findViewById(R.id.A2_option2);
qa2Option2.setText(Nature.BIRD);
// add emoji A2_option3
TextView qa2Option3 = findViewById(R.id.A2_option3);
qa2Option3.setText(Nature.HORSE);
//Q3 audio
Button q3Sound = this.findViewById(R.id.Q3_sound);
final MediaPlayer q3 = MediaPlayer.create(this, R.raw.camel);
q3Sound.setOnClickListener(new OnClickListener() {
public void onClick(View v) { q3.start();
}
});
// add emoji Q4_question
TextView q4 = findViewById(R.id.Q4_question);
q4.setText(Nature.ANT);
// Start of spinner Q4
Spinner a4 = findViewById(R.id.A4);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence>adapter = ArrayAdapter.createFromResource(this,
R.array.a4_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
a4.setAdapter(adapter);
a4.setOnItemSelectedListener(this);
//Q5 audio
Button q5Sound = this.findViewById(R.id.Q5_sound);
final MediaPlayer q5 = MediaPlayer.create(this, R.raw.cow_bird);
q5Sound.setOnClickListener(new OnClickListener() {
public void onClick(View v) { q5.start();
}
});
//A5
// add emoji A5_option1
TextView qa5Option1 = findViewById(R.id.A5_option1);
qa5Option1.setText(Nature.COW);
// add emoji A5_option2
TextView qa5Option2 = findViewById(R.id.A5_option2);
qa5Option2.setText(Nature.PIG);
// add emoji A5_option3
TextView qa5Option3 = findViewById(R.id.A5_option3);
qa5Option3.setText(Nature.SNAKE);
// add emoji A5_option4
TextView qa5Option4 = findViewById(R.id.A5_option4);
qa5Option4.setText(Nature.BIRD);
}
//Display Result
public void results(View view){
// Check point for Q1
EditText a1EditText = findViewById(R.id.A1);
String a1Entry = a1EditText.getText().toString();
if (a1Entry.contains("نحلة")) {
arabicScore = arabicScore + 1;
}
// Check point for Q2
RadioButton a2Radio = findViewById(R.id.A2_option2);
boolean isa2RadioChecked = a2Radio.isChecked();
if (isa2RadioChecked){
arabicScore = arabicScore + 1;
}
// Check point for Q3
EditText a3EditText = findViewById(R.id.A3);
String a3Entry = a3EditText.getText().toString();
if (a3Entry.contains("جمل")) {
arabicScore = arabicScore + 1;
}
// Check point for Q4
Toast resultToast = Toast.makeText(this, "You got " + arabicScore + " of 7 questions right.", Toast.LENGTH_LONG);
resultToast.show();
}
Preview of layout
}
Thank you very much for your advice in advance! I've been stuck on this for months! :'D

Sugar ORM how do i add data to a row in the table

Good day all i am using android studio, I have a fairly good idea of how to use sugar ORM at this point, but there's one thing that I just cant find or figure out.
So i have an activity named UserProfiles.java in which i ask the user for various things and then i store them in the database. So at this point i have about 20 records/rows in the database. The problem however is when i send the user to the next activity (UserPins.java) i ask them to set some additional information now how do i add this information to the same line as the data that has the User Profiles information?
//this is my UserProfiles.java
package com.chika.mia;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.chika.mia.models.Mia;
public class UserProfile extends AppCompatActivity implements View.OnClickListener {
private EditText Name, PhoneNumber, Email, Password, Address;
private Button SaveUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
Name = (EditText)findViewById(R.id.Name);
PhoneNumber = (EditText)findViewById(R.id.PhoneNumber);
Email = (EditText)findViewById(R.id.Email);
Password = (EditText)findViewById(R.id.Password);
Address = (EditText)findViewById(R.id.Address);
SaveUser = (Button)findViewById(R.id.SaveUser);
SaveUser.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Mia m = new Mia();
m.setName(register.g);
m.setPhoneNumber(Integer.parseInt(PhoneNumber.getText().toString())) ;
m.setEmail(register.i) ;
m.setPassword(register.h);
m.setAddress(Address.getText().toString()) ;
m.setLocation("MiaL");
m.setWipePhone("MiaWP");
m.setDispMessage("MiaDM");
m.setAlarm("MIAA");
m.setShutdown("MIASD");
m.save();
Toast.makeText(this, " " + m.getName(), Toast.LENGTH_LONG).show();
Intent intent = new Intent(UserProfile.this, UserPins.class);
startActivity(intent);
}
}
And this is my Userpins.java
package com.chika.mia;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import com.chika.mia.models.Mia;
import com.orm.query.Condition;
import com.orm.query.Select;
public class UserPins extends AppCompatActivity implements View.OnClickListener {
private EditText UserLocation,UserWipePhone,UserDisplayMsg,UserAlarm,UserShurdown;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_pins);
UserLocation = (EditText)findViewById(R.id.UserLocation);
UserWipePhone = (EditText)findViewById(R.id.UserWipePhone);
UserDisplayMsg = (EditText)findViewById(R.id.UserDisplayMsg);
UserAlarm = (EditText)findViewById(R.id.UserAlarm);
UserShurdown = (EditText)findViewById(R.id.UserShutdown);
}
#Override
public void onClick(View v) {
Mia m = new Mia();
Select.from(Mia.class).where(Condition.prop("Name").eq(register.i)).list();
m.setLocation(UserLocation.getText().toString());
m.setWipePhone(UserWipePhone.getText().toString());
m.setDispMessage(UserDisplayMsg.getText().toString());
m.setAlarm(UserAlarm.getText().toString());
m.setShutdown(UserShurdown.getText().toString());
m.update();
Intent intent = new Intent(this,AppSettings.class);
startActivity(intent);
}
}
What am aiming to do is something like this, So for which ever user logs in say "Tom", i already have the login and registration page sorted out. It will go through the database and look for the name "Tom" or email "tom#gmail.com" and then add the userpins information to the appropriate column in that table.
When you create a new record in Sugar ORM, you get a unique ID back from the save(). On your first activity, get the ID, and pass it to the next activity:
long new_user_id = m.save();
...
Intent intent = new Intent(UserProfile.this, UserPins.class);
intent.putExtra("NEW_USER_ID", new_user);
startActivity(intent);
Then you can grab it in the new activity with:
long new_user_id = getIntent().getLongExtra("NEW_USER_ID",0);
You may then use the ID to get the record to update:
Mia m = Mia.findById(Mia.class, new_user_id);

Cannot set Gmail 'subject' and 'text' fields from an intent

I am calling an intent that sets the 'To' field no problem of a GMail template from a String array, but I cannot get it to set the 'subject' and 'text' fields.
Hopefully someone can see where I'm going wrong
Here's my code:
package com.example.flybase2;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class ContactsEmail extends Activity implements OnClickListener{
String emailPassed;
String emailAdd;
String emailSub;
String emailMess;
EditText setEmailAddress;
EditText setEmailSubject;
EditText setEmailMessage;
Button btnSendEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.emaillayout);
Bundle extras = getIntent().getExtras();
if (extras != null) {
emailPassed = extras.getString("passedEmailAdd");
}
setEmailAddress = (EditText) findViewById (R.id.inputEmailAddress);
setEmailAddress.setText(emailPassed);
setEmailSubject = (EditText) findViewById (R.id.inputEmailSubject);
setEmailMessage = (EditText) findViewById (R.id.inputEmailMessage);
emailAdd = setEmailAddress.getText().toString();
emailSub = setEmailSubject.getText().toString();
emailMess = setEmailMessage.getText().toString();
btnSendEmail = (Button)findViewById(R.id.btnSendEmail);
btnSendEmail.setOnClickListener(this);
}
#Override
public void onClick(View sendEmailClick) {
Intent sendEmailIntent = new Intent(Intent.ACTION_SEND);
sendEmailIntent.setType("plain/text");
sendEmailIntent.putExtra(Intent.EXTRA_EMAIL,new String[] {emailAdd});
sendEmailIntent.putExtra(Intent.EXTRA_SUBJECT, emailSub);
sendEmailIntent.putExtra(Intent.EXTRA_TEXT, emailMess);
startActivity(Intent.createChooser(sendEmailIntent, "Send mail..."));
}
}
Try this.
Actually When activity create you get the value of these editext. At that time value of these all are empty. so you need to write these in onclick method.
When you click on button then you will get the current edit text value.
I hope this will solve your problem.
#Override
public void onClick(View sendEmailClick) {
emailAdd = setEmailAddress.getText().toString();
emailSub = setEmailSubject.getText().toString();
emailMess = setEmailMessage.getText().toString();
Intent sendEmailIntent = new Intent(Intent.ACTION_SEND);
sendEmailIntent.setType("plain/text");
sendEmailIntent.putExtra(Intent.EXTRA_EMAIL,new String[] {emailAdd});
sendEmailIntent.putExtra(Intent.EXTRA_SUBJECT, emailSub);
sendEmailIntent.putExtra(Intent.EXTRA_TEXT, emailMess);
startActivity(Intent.createChooser(sendEmailIntent, "Send mail..."));
}
and remove these three lines from onCreate() method.
emailAdd = setEmailAddress.getText().toString();
emailSub = setEmailSubject.getText().toString();
emailMess = setEmailMessage.getText().toString();

Categories