So I am creating an android application which opens the url entered by the user. Now each time an url is entered by the user, it needs to be save using the "save" button and the save list is seen using the "list" button.
This is my Interface:
This is my xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="#+id/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.application.mota_app.MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:text="#string/enter_the_url_below"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/enter_URL"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="26dp"
android:textSize="19sp"
android:textColor="#android:color/holo_green_dark" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/txtbox_website"
android:layout_marginTop="18dp"
android:width="300dp"
android:inputType="textUri"
android:layout_below="#+id/enter_URL"
android:layout_centerHorizontal="true" />
<Button
android:text="#string/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_save"
android:textColor="#color/colorAccent"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:text="#string/visit"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="#+id/btn_visit"
android:textColor="#android:color/holo_blue_dark"
android:onClick="open"
android:layout_marginBottom="50dp"
android:layout_alignBottom="#+id/btn_save"
android:layout_centerHorizontal="true" />
<Button
android:text="#string/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_list"
android:textColor="?android:attr/colorPressedHighlight"
android:layout_below="#+id/btn_save"
android:layout_alignLeft="#+id/btn_save"
android:layout_alignStart="#+id/btn_save" />
</RelativeLayout>
So I am stuck in the save and list. I am using shared preferences, but I am not able to save and list the URLS. This is the code I wrote:
public class MainActivity extends AppCompatActivity {
public static final String MY_EMP_PREFS = "MyPrefs";
private EditText url;
private Button save;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
url = (EditText)findViewById(R.id.txtbox_website);
save = (Button)findViewById(R.id.btn_save);
}
public void open(View view){
if (url.getText().toString().matches("")) {
Toast.makeText(getApplicationContext(), "Enter a website to open!", Toast.LENGTH_SHORT).show();
return;
}
if (!url.getText().toString().startsWith("http://") && !url.getText().toString().startsWith("https://"))
{
url.setText("http://" + url.getText().toString());
}
if (!Patterns.WEB_URL.matcher(url.getText().toString()).matches())
{
Toast.makeText(getApplicationContext(), "Invalid URL!", Toast.LENGTH_SHORT).show();
url.setError("Enter a valid URL");
url.setText("");
url.setSelection(0);
return;
}
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url.getText().toString()));
startActivity(browserIntent);
}
public void save(View view) {
SharedPreferences pref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
// We need an editor object to make changes
SharedPreferences.Editor edit = pref.edit();
// Set/Store data
edit.putString("save", url.getText().toString());
// Commit the changes
edit.commit();
Toast.makeText(getApplicationContext(), "URL Saved", Toast.LENGTH_SHORT).show();
}
Where am I going wrong? What should I do?
Thanks
You have to add the method reference in your Widget:
<Button
android:text="#string/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_save"
android:onClick="save" //HERE
android:textColor="#color/colorAccent"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
Also, when you use a SharedPreferences, you are putting a String value using the key "save". So when you click on save button, you are overriding the old value and put a new value in the place.
To solve this issue, I think the best solution is use a Framework to persist the data and list it after.
edit.putString("save", url.getText().toString()); //here you are overriding the vlaue
Related
My application has an authentication service made in .net and SSMS(SQL Server)
In one of my activities, I want to store a TextView value (that is incrementing due to the user using the application) so that each user has his own value. For example, user 1 uses the application 1h and closes the application. If user 2 logins in the app, the value should be different. When user 1 logins again, the value should be the last one before he closes the app.
Which method should I use in this case? Should I use SharedPreferences?
EDIT 08/09/2020
UserPoints.java
public class UserPoints extends AppCompatActivity{
private TextView userMoneyTV;
private BroadcastReceiver minuteUpdateReceiver;
private int userMoney = 0;
private Button saveMoney, loadMoney;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_points);
userMoneyTV = (TextView) findViewById(R.id.userMoney);
final String UserMoney = userMoneyTV.getText().toString();
saveMoney = (Button) findViewById(R.id.saveMoney);
saveMoney.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences preferences = getSharedPreferences("MYPREFS",MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("money", UserMoney);
editor.putString("email", String.valueOf(R.id.email));
editor.commit();
}
});
loadMoney = (Button) findViewById(R.id.loadMoney);
loadMoney.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences preferences = getSharedPreferences("MYPREFS",MODE_PRIVATE);
String money = preferences.getString("money",UserMoney);
String email = preferences.getString("email",String.valueOf(R.id.email));
userMoneyTV.setText(money);
}
});
}
public void startMinuteUpdateReceiver(){
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_TIME_TICK);
minuteUpdateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
userMoney++;
userMoneyTV.setText(""+ userMoney);
}
};
registerReceiver(minuteUpdateReceiver,intentFilter);
}
#Override
protected void onResume() {
super.onResume();
startMinuteUpdateReceiver();
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(minuteUpdateReceiver);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
activity_user_points.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/rewardLayout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="#+id/rewardInfoLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="10dp">
<ImageView
android:id="#+id/chestReward"
android:layout_width="200dp"
android:layout_height="150dp"
android:layout_marginTop="120dp"
android:src="#drawable/chestreward"
android:layout_alignParentLeft="true">
</ImageView>
<TextView
android:id="#+id/rewardText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="0dp"
android:layout_marginBottom="68dp"
android:layout_toRightOf="#+id/chestReward"
android:text="Earn money every minute you use the app"
android:layout_marginTop="175dp">
</TextView>
</RelativeLayout>
<RelativeLayout
android:id="#+id/moneyInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="#+id/rewardInfoLayout">
<TextView
android:id="#+id/userMoneyText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:fontFamily="casual"
android:text="Your Money: "></TextView>
<TextView
android:id="#+id/userMoney"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:layout_toRightOf="#+id/userMoneyText"
android:layout_marginTop="20dp">
</TextView>
<TextView
android:id="#+id/euro"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="€"
android:layout_toRightOf="#+id/userMoney"
android:layout_marginTop="20dp"
android:layout_marginLeft="5dp">
</TextView>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/moneyInfo">
<Button
android:id="#+id/saveMoney"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save Money"
android:layout_marginTop="10dp"
android:layout_centerHorizontal="true"
android:onClick="startVideoAd">
</Button>
<Button
android:id="#+id/loadMoney"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Load Money"
android:layout_marginTop="10dp"
android:layout_centerHorizontal="true"
android:layout_below="#+id/saveMoney">
</Button>
</RelativeLayout>
</RelativeLayout>
EDIT 9/9/2020
My problem was solved with EDIT 8/9/2020
Now my question is, how can i make the value increasing when i'm in another activity? AsyncTask?
Yes, you can use the SharedPreferences but if the user uninstalls the application user will lose its data and the value you've stored in SharedPreferences.
And if you want to save data even after uninstalling the app you can use any lightweight database i.e. Realm,Room,SQLite,Firebase and store your local database in users sd card. Else use Google backup service or store it in another place like on your server.
I'm trying to build an app where someone can fill in their personal data like their name, telephone number, Email...
For each field mentioned above, I created an EditText. Now my goal is to save the user's input using SharedPreferences so that he/she don't have to fill it up every time they reopen the app.
The codes I've found take care of saving the data for one EditText only (Save entered text in editText via button). How can I achieve that on multiple EditText fields?
This is my XML file below:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Vul dit compleet in"
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textColor="#000066"
android:textStyle="bold"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Naam: "
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textColor="#000066"
android:textStyle="bold"/>
<EditText
android:id="#+id/edit_Naam"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textColor="#000066"
android:hint="Vul uw naam in"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Functie: "
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textColor="#000066"
android:textStyle="bold"/>
<EditText
android:id="#+id/edit_Functie"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textColor="#000066"
android:hint="Vul uw functie in"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Personeelsnummer "
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textColor="#000066"
android:textStyle="bold"/>
<EditText
android:id="#+id/edit_Plnr"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textColor="#000066"
android:hint="Vul uw plnr in"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email: "
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textColor="#000066"
android:textStyle="bold"/>
<EditText
android:id="#+id/edit_Email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textColor="#000066"
android:hint="NS mail"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Telefoon: "
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textColor="#000066"
android:textStyle="bold"/>
<EditText
android:id="#+id/edit_Telefoon"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textColor="#000066"
android:hint="zonder +31"/>
<Button
android:id="#+id/button_Opslaan"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_below="#+id/edit_Bericht"
android:layout_centerHorizontal="true"
android:layout_marginBottom="48dp"
android:layout_weight="0.03"
android:background="#009CDE"
android:drawableLeft="#drawable/ic_launcher"
android:text="Opslaan"
android:textColor="#FFFFFF"/>
</LinearLayout>
</ScrollView>
You just have to save each EditText value and retrieve them next time your Activity reloads. The code below is adapted from the link you mentioned in your question:
public class PersonalInformation extends Activity{
private SharedPreferences savedFields;
private Button saveButton;
private EditText editText1;
private EditText editText2;
// Add all your EditTexts...
// Upon creating your Activity, reload all the saved values.
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
saveButton = (Button) findViewById(R.id.your_save_button_id);
editText1 = (EditText) findViewById(R.id.your_edit_text_1_id);
editText2 = (EditText) findViewById(R.id.your_edit_text_2_id);
// Keep adding all your EditTexts the same way...
// "info" is just a tag name, use anything you like
savedFields = getSharedPreferences("info", MODE_PRIVATE);
// In case no value is already saved, use a Default Value
editText1.setText(savednotes.getString("editText1", "Default Value 1"));
editText2.setText(savednotes.getString("editText2", "Default Value 2"));
// Save the changes upon button click
saveButton.setOnClickListener(saveButtonListener);
}
public OnClickListener saveButtonListener = new OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor preferencesEditor = savedFields.edit();
if(editText1.getText().length() > 0) // Not empty
preferencesEditor.putString("editText1", editText1.getText());
if(editText2.getText().length() > 0) // Not empty
preferencesEditor.putString("editText2", editText2.getText());
// You can make a function so you woudn't have to repeat the same code for each EditText
// At the end, save (commit) all the changes
preferencesEditor.commit();
}
}
};
}
Try this to store in shared preferences
// MY_CONTAINER - a static String variable like:
//public static final String MY_CONTAINER = "MyPrefsFile";
SharedPreferences.Editor editor = getSharedPreferences(MY_CONTAINER , MODE_PRIVATE).edit();
editor.putString("edittext1", "value1"); // you can also use like this editor.putString("edittext1", ed1.getText().toString())
editor.putString("edittext2", "value2");
editor.putString("edittext3", "value3");
editor.putString("edittext4", "value4");
editor.putString("edittext5", "value5");
editor.commit();
To retrieve
SharedPreferences prefs = getSharedPreferences(MY_CONTAINER, MODE_PRIVATE);
String edit1 = prefs.getString("edittext1");
String edit2 = prefs.getString("edittext2");
String edit3 = prefs.getString("edittext3");
String edit4 = prefs.getString("edittext4");
String edit5 = prefs.getString("edittext5");
I am new in android development. I start for android accessibility work to make android application accessible for blind people. I made simple login form and set accessibility attribute such as content description and focus etc I turn on talk back and check it.
here is code activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
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"
tools:context=".MainActivity"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/usernm_text"
android:id="#+id/username"
android:contentDescription="#string/usernm_text"
android:focusable="true"
android:nextFocusDown="#+id/usr_nm"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/usr_nm"
android:contentDescription="#string/usernm_text"
android:focusable="true"
android:text="admin"
android:nextFocusDown="#+id/password"
android:nextFocusUp="#id/usr_nm"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/pass_text"
android:id="#+id/password"
android:focusable="true"
android:nextFocusDown="#+id/pass_edit"
android:contentDescription="#string/pass_text"
android:nextFocusUp="#id/usr_nm"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="#+id/pass_edit"
android:contentDescription="#string/pass_text"
android:text="admin"
android:focusable="true"
android:nextFocusDown="#+id/login"
android:nextFocusUp="#id/password"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/login_btn"
android:onClick="log"
android:id="#+id/login"
android:contentDescription="#string/login_btn"
android:focusable="true"
android:nextFocusUp="#id/pass_edit"
android:accessibilityLiveRegion="polite" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/log_succ"
android:focusable="true"
android:accessibilityLiveRegion="polite" />
</LinearLayout>
in my MainActivity.java
public class MainActivity extends AppCompatActivity {
EditText usr_nm;
TextView log_succ;
Button logs;
EditText pass_edit;
int counter=5;
String log_msg="login successful";
Button log_btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
log_succ=(TextView) findViewById(R.id.log_succ);
usr_nm=(EditText) findViewById(R.id.usr_nm);
pass_edit=(EditText)findViewById(R.id.pass_edit);
}
public void log(View view) {
if (usr_nm.getText().toString().equals("admin") &&
pass_edit.getText().toString().equals("admin")) {
log_succ.setText(log_msg);
log_succ.setContentDescription("Login successful");
// log_succ.isFocusable();
// Toast.makeText(MainActivity.this, "password is correct", Toast.LENGTH_LONG).show();
// Intent in = new Intent("com.example.samir.login_form.user_page");
// startActivity(in);
} else {
Toast.makeText(MainActivity.this, "password is incorrect", Toast.LENGTH_SHORT).show();
counter--;
if (counter == 0)
logs.setEnabled(false);
}
}
login successful textview prompt by talkback when touch it.
i want that when i click on login button then textview "Login successful" should be prompt by talkback immediately.
I set AccessibilityliveRegion to "polite".
what else should i do??
From what i understood, you want the system to speak up "Login Successful" after the user logs in.
You can achieve this using TextToSpeech class.
First declare an object of TextToSpeech (a Global/Class variable):
TextToSpeech tts;
Then set it to instantiate & speak up when your login process is successful:
tts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status == TextToSpeech.SUCCESS){
tts.setLanguage(Locale.US);
tts.speak("Login Successful", TextToSpeech.QUEUE_FLUSH, null);
}
}
});
Also, don't forget to release the resources after you are done:
#Override
protected void onPause() {
if(tts!=null){
tts.stop();
tts.shutdown();
}
super.onPause();
}
Hope this helps.
This is possible if we set android:accessibilityLiveRegion="polite" for textview .. thank you for your reply.
i've a problem. I want to make a app with a loggin activity and a main activity. (To the OnClickListiner later)
fist:
What ive done so far:
i've created a login. java and login.xml
login.java:
public class Login extends Activity implements OnClickListener {
Button btnStartAnotherActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
boolean hasLogedIn = true;
if (hasLogedIn) {
Intent i = new Intent(Login.this, MainActivity.class);
startActivity(i);
finish();
} else {
}
}
public void onClick(View view) {
//calling an activity using <intent-filter> action name
Intent inent = new Intent("android.name.MainActivity ");
startActivity(inent);
}
}
i've created a MainActivity.java and activity_main.xml
moreover i've some other java and xml files to make a materiel designed Tab view for my MainActivity.
i have 3 tabs thats how it looks so far
[![tab1 with buttons][1]][1]
-now i'be added to the first tab 3 buttons.
example of one button: (the others are the same just a other id )
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Kommt"
android:clickable="false"
android:textColor="#190707"
android:id="#+id/kommt"
android:layout_alignParentStart="true"
android:layout_below="#+id/space" />
-So the app is running now without problems. ( All Tabs and there content is showing like i want it )
when i build the project the mainactivity is open first( see that link of the picture )
HOW TO SET: the login interface to be started once, when starting the app for the first time. After login is succesfully, then the mainactivity will always open. Thats my first problem. What should i add to the Login.java ? and how to set that the login.xml starts before the mainactivity ?
Second:
As i told you ive added some buttons. To test the buttons i've tried to implement a code for toast notification when clicking on button. But every time i build the project with the toast notifitcation code, the app doenst start anymore. Here the code for the toast notification i'm using:
public class MainActivity extends ActionBarActivity implements OnClickListener {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // but my main_activity doesnt have buttons ... tab1.xml have b
Button kommtbutton;
kommtbutton= (Button) findViewById(R.id.kommt);
kommtbutton.setOnClickListener(this);}
#Override
public void onClick(View v) {
setContentView(R.layout.tab1); // not sure if this is right ive did it cause the buttons are in the tab1 layout and not main_activity
switch(v.getId())
{
case R.id.kommt:
{
Toast toast1 = Toast.makeText(getApplicationContext(),
"Eingestempelt",
Toast.LENGTH_SHORT);
toast1.show();
break;
} ....}
here i have implemented all 3 buttons in a switch case.
It looks right but the onclicklistinier seems to kill my application before it can start. Maybe someone can help me.
i have following files:
Login.java, MainActivity.java, Tab1.java,Tab2.java,Tab3.java, SlidingTabsLayout.java, SlidingTabStrip.java and ViewPagerAdaper.
and i have this layouts.
acitivy_main.xml, login.xml, tab1,tab2,tab3.xml, toolbar.xml.
I'm not allowed to send pictures cause i'm new here.
Where have i do implement the code for the toast notification ?
thats my activity_main:xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<include
android:id="#+id/tool_bar"
layout="#layout/tool_bar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
/>
<android_package.SlidingTabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="2dp"
android:background="#color/ColorPrimary"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_weight="1"/>
and this is my tab1.xml
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/Tabs"
android:background="#FDFDFE"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/buchungen"
android:textColor="#190707"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Geht"
android:clickable="false"
android:textColor="#190707"
android:id="#+id/geht"
android:layout_alignParentBottom="true"
android:layout_alignEnd="#+id/textClock"
android:layout_marginBottom="36dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Name:"
android:paddingBottom="7dp"
android:paddingTop="7dp"
android:textColor="#190707"
android:id="#+id/name"
android:layout_alignParentStart="true"
android:layout_below="#+id/buchungen" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#190707"
android:paddingBottom="7dp"
android:paddingTop="7dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Status:"
android:id="#+id/status"
android:layout_below="#+id/name"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#190707"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Letzte Buchung:"
android:paddingBottom="4dp"
android:paddingTop="7dp"
android:id="#+id/letzteBuchung"
android:layout_below="#+id/status"
android:layout_alignParentStart="true" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_alignBottom="#+id/buchungen"
android:weightSum="1"
android:id="#+id/linearLayout">
<ImageView
android:layout_width="314dp"
android:layout_height="310dp"
android:id="#+id/profilbild"
android:layout_gravity="center_horizontal"
android:src="#drawable/time" />
</LinearLayout>
<Space
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_above="#+id/geht"
android:id="#+id/space" />
<TextClock
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#190707"
android:id="#+id/textClock"
android:layout_alignTop="#+id/name"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Kommt"
android:clickable="false"
android:textColor="#190707"
android:id="#+id/kommt"
android:layout_alignParentStart="true"
android:layout_below="#+id/space" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Pause An/Aus"
android:textColor="#190707"
android:id="#+id/textView"
android:layout_alignTop="#+id/textView3"
android:layout_alignStart="#+id/pause" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Einstempeln"
android:textColor="#190707"
android:id="#+id/textView2"
android:layout_above="#+id/kommt"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Ausstempeln"
android:textColor="#190707"
android:id="#+id/textView3"
android:layout_alignBottom="#+id/geht"
android:layout_alignStart="#+id/geht"
android:layout_alignTop="#+id/textView2" />
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pause"
android:textColor="#190707"
android:id="#+id/pause"
android:layout_alignBottom="#+id/kommt"
android:layout_centerHorizontal="true"
android:checked="false" />
</RelativeLayout>
The buttons are in the tab1.xml. Where have i to acces them to make a Interaction ( show toast when pressing the button ) ? in the MainActivity.java or the Tab1.java or somewhere else ?
When i try to add toast notification my app just kills itself ...
You have to put all the findViewById and setContentView in the onCreate method or they won't do the job.
First point :
public class MainActivity extends ActionBarActivity
{
// Layout elements
private Button kommtbutton = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Attach layout
setContentView(R.layout.activity_main); // but my main_activity doesnt have buttons ... tab1.xml have b
// Retrieve layout elements
kommtbutton= (Button) findViewById(R.id.kommt);
// Attach listeners
kommtbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view)
{
// Do not use getApplicationContext(), this is an activity
Toast.makeText(MainActivity.this, "Eingestempelt", Toast.LENGTH_SHORT).show();
}
});
}
[...]
}
Second point :
public class LoginActivity extends Activity
{
// Layout elements
private EditText edit_login = null;
private EditText edit_password = null;
private Button btn_login = null;
// Class variables
private SharedPreferences prefs = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Check if the user is already logged in
prefs = getSharedPreferences(getPackageName(), MODE_PRIVATE);
if (prefs.getBoolean("isLoggedIn", false))
{
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
return;
}
// Attach layout
setContentView(R.layout.login);
// Retrieve layout elements
edit_login = (EditText) findViewById(R.id.edit_login);
edit_password = (EditText) findViewById(R.id.edit_password);
btn_login = (Button) findViewById(R.id.btn_login);
// Attach listeners
btn_login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view)
{
// Retrieve information
String login = edit_login.getText().toString();
String password = edit_password.getText().toString();
// Do job
boolean canConnect = true; // TODO
if (canConnect)
{
// Update prefs
prefs.edit().putBoolean("isLoggedIn", true).commit();
// Move to activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
else
{
// Update prefs
prefs.edit().putBoolean("isLoggedIn", false).commit();
// Display error message
Toast.makeText(LoginActivity.this, "Wrong crendentials", Toast.LENGTH_LONG).show();
}
}
});
}
}
In my project, im going to make a multiple choice type question. I can select the questions and answer from mysql, however, i cant do the "matching" of the answer between input answer and the data from mysql. I tried some solutions but they doesnt work as well. I need a big help on it. Below are my codes.
the java class that make multiple choice
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.normalmode);
new DataAsyncTask().execute();
}
public void onClick(View v){
inputtext = ((Button) v).getText().toString();
tv3 = (TextView)findViewById(R.id.textView3);
tv3.setText(inputtext);
if(inputtext == tv2.getText().toString()){
playerscore +=5;
} else {
playerscore +=1;
}
score.setText("Scores : " + playerscore);
new DataAsyncTask().execute();
}
class DataAsyncTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... param) {
String result = DBConnector.executeQuery("SELECT * FROM questions ORDER BY RAND( ) LIMIT 1");
return result;
}
#Override
protected void onPostExecute(String result) {
question = (TextView)findViewById(R.id.textView_question);
fchoice = (Button)findViewById(R.id.Btn_choice1);
schoice = (Button)findViewById(R.id.Btn_choice2);
tchoice = (Button)findViewById(R.id.Btn_choice3);
tv2 = (TextView)findViewById(R.id.textView2);
score = (TextView)findViewById(R.id.textView_score);
try {
JSONArray jsonArray = new JSONArray(result);
JSONObject jsonData = jsonArray.getJSONObject(0);
question.setText(jsonData.getString("q_desc"));
fchoice.setText(jsonData.getString("fchoice"));
schoice.setText(jsonData.getString("schoice"));
tchoice.setText(jsonData.getString("tchoice"));
ans = jsonData.getString("q_ans");
tv2.setText(ans);
} catch(Exception e) {
Log.e("log_tag", e.toString());
}
}
}
}
three buttons are sharing same onClick in xml file by using
android:onClick="onClick"
the current problem i faced is that it always return "false" no matter i pressed which button. also, is there any way to store/pass "previous" async task data?
I have tried using internal storage but it doesnt work as well
EDIT:
my xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.95" >
<TextView
android:id="#+id/textView_score"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/player_score" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.95" >
<TextView
android:id="#+id/textView_question"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/string_question"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/Btn_choice3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:text="#string/third_choice"
android:onClick="onClick" />
<Button
android:id="#+id/Btn_choice2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/Btn_submit"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:text="#string/second_choice"
android:onClick="onClick" />
<Button
android:id="#+id/Btn_choice1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/Btn_choice2"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:text="#string/first_choice"
android:onClick="onClick" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="TextView" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/textView1"
android:text="TextView" />
</RelativeLayout>
</LinearLayout
textview2 and textview3 are used to test my output and display them as text
try this if(inputtext.equals(tv2.getText().toString())) instead of if(inputtext == tv2.getText().toString())
becasue the == operator checks to see if the two strings are exactly the same object.
The .equals() method will check if the two strings have the same value.