Error when I push MySQL data with onPostExecute - java

I'm new at programming. I'm doing a login system, but when I log in, I get that error. I don’t know how to solve it. And I have one more question: Is making a login system with chat and friends (add, Remove) system too hard?
Because I want to do that, but I just started programming one week ago, can I do this?
FATAL EXCEPTION: main
Process: complete.lyne.myapplication, PID: 18933
java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
at complete.lyne.myapplication.Login$SolicitaDados.onPostExecute(Login.java:110)
at complete.lyne.myapplication.Login$SolicitaDados.onPostExecute(Login.java:91)
at android.os.AsyncTask.finish(AsyncTask.java:660)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:677)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Here is my code:
package complete.lyne.myapplication;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
// import br.com.simplepass.loading_button_lib.customViews.CircularProgressButton;
public class Login extends AppCompatActivity {
EditText loginEmail, loginSenha;
Button btLogar;
TextView refCadastrar;
String url = "";
String parametro = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
loginEmail = (EditText)findViewById(R.id.loginEmail);
loginSenha = (EditText)findViewById(R.id.loginSenha);
btLogar = (Button)findViewById(R.id.btLogar);
refCadastrar = (TextView)findViewById(R.id.refCadastrar);
refCadastrar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent abreCadastro = new Intent(Login.this, Cadastro.class);
startActivity(abreCadastro);
}
});
btLogar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ConnectivityManager connectivityManager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
String email = loginEmail.getText().toString();
String senha = loginSenha.getText().toString();
if(email.isEmpty() && senha.matches(".*[a-z].*")) {
loginEmail.setError("Insira seu endereço de Email.");
} else if (email.matches(".*[a-z].*") && senha.isEmpty()) {
loginSenha.setError("Insira sua Senha.");
} else if (email.isEmpty() && senha.isEmpty()) {
Toast.makeText(getApplicationContext(), "Nenhum campo pode ficar vazio.", Toast.LENGTH_LONG).show();
} else {
// Casa
url = "http://192.168.1.100/lyne/logar.php";
// Badran
// url = "http://172.16.2.15/lyne/logar.php";
parametro = "email=" + email + "&senha=" + senha;
new SolicitaDados().execute(url);
}
}
else {
Toast.makeText(getApplicationContext(), "Nenhuma conexão com a Internet foi encontrada.", Toast.LENGTH_LONG).show();
}
}
});
}
private class SolicitaDados extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return Conexao.postDados(urls[0], parametro);
}
#Override
protected void onPostExecute(String resultado) {
if(resultado != null) {
if (resultado.contains("login_ok")) {
String[] dados = resultado.split(",");
Intent abreHome = new Intent(Login.this, Home.class);
abreHome.putExtra("idusu", dados[1]);
abreHome.putExtra("nomeusu", dados[2]);
startActivity(abreHome);
} else {
Toast.makeText(getApplicationContext(), "Usuário ou senha incorretos.", Toast.LENGTH_LONG).show();
}
}
}
}
#Override
protected void onPause() {
super.onPause();
finish();
}
}

You are asking for an index that doesn't exist inside of you array.
It seems like you're looking for two objects, not three, but you are looking in the wrong place.
You should edit your code to look like this:
abreHome.putExtra("idusu", dados[0]);
abreHome.putExtra("nomeusu", dados[1]);

You are splitting the string:
String[] dados = resultado.split(",");
And assuming there will be at least three pieces:
abreHome.putExtra("idusu", dados[1]);
abreHome.putExtra("nomeusu", dados[2]);
But looks like that's is not the case. Check for the length of dados before you go and access elements from it.

Related

Didn't Understand which data type is name.gettext().tostring()

I am building an app that toastes Welcome when only specific email and password is inputted. Otherwise it says Incorrect Email/password. But I don't understand what the problem with my code is. I think the problem is within string.gettext().toString(). I do not know how to use it in the if-else-loop...
package com.example.project2;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class Project2 extends AppCompatActivity {
public void login(View view) {
EditText email = (EditText) findViewById(R.id.emailEditText);
EditText password = (EditText) findViewById(R.id.passwordEditText);
Log.i("info","Button pressed!");
String Email = email.getText().toString();
String Password = password.getText().toString();
boolean email1 = Email.contains("example876#gmail.com");
boolean password1 = Password.contains("asad123");
if (email1){
Toast.makeText(this, "Welcome", Toast.LENGTH_LONG).show();
} else if (password1) {
Toast.makeText(this, "The method worked", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Incorrect Username/Password", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_project2);
}
}
Somebody plz help!!
THanks in advance...

App crashes when TextInputLayout empty and button is clicked

I am trying to make the EditTextLayout makes an error message when they are empty and the app crashes
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class LoginActivity extends AppCompatActivity {
private TextInputLayout textInputEmail , textInputPassword;
private Button login;
String emailInput , passwordInput;
private FirebaseAuth auth;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
auth = FirebaseAuth.getInstance();
textInputEmail = (TextInputLayout) findViewById(R.id.login_email);
textInputPassword = (TextInputLayout) findViewById(R.id.login_password);
login = (Button)findViewById(R.id.login_button);
progressDialog = new ProgressDialog(this);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ConfirmInput();
progressDialog.setTitle("Singing in");
progressDialog.setMessage("Please wait while we sign you in");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
auth.signInWithEmailAndPassword(emailInput , passwordInput).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
progressDialog.dismiss();
Toast.makeText(LoginActivity.this, "Account Created successfuly", Toast.LENGTH_SHORT).show();
SendUserToMainActivity();
}else{
progressDialog.dismiss();
Toast.makeText(LoginActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
private void SendUserToMainActivity() {
Intent intent = new Intent(LoginActivity.this , MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
public boolean ValidateEmail(){
emailInput = textInputEmail.getEditText().getText().toString().trim();
if(emailInput.isEmpty()){
textInputEmail.setError("You Can't leave this Empty!");
return false;
}else{
textInputEmail.setError(null);
return true;
}
}
public boolean ValidatePassword(){
passwordInput = textInputPassword.getEditText().getText().toString();
if(passwordInput.isEmpty()){
textInputPassword.setError("You Can't leave this Empty!");
return false;
}else{
textInputPassword.setError(null);
return true;
}
}
public void ConfirmInput(){
if(!ValidateEmail() | !ValidatePassword()){
return;
}
}
}
java.lang.IllegalArgumentException: Given String is empty or null
at com.google.android.gms.common.internal.zzbq.zzgm(Unknown Source)
at com.google.firebase.auth.FirebaseAuth.signInWithEmailAndPassword(Unknown Source)
at com.example.bestever.snapchatclone.LoginActivity$1.onClick(LoginActivity.java:50)
at android.view.View.performClick(View.java:5184)
at android.view.View$PerformClick.run(View.java:20893)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5938)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
I tried also to change The TextInputLayout to TextInputEditText and nothing changed. I also tried to change my approach for checking if the TextInputLayout is empty, but it doesn't work
You should validate if textInputEmail.getEditText().getText() is null before retrieving the text from it, that might be the problem. Hope it works.
You can't call getText() function on null String.
Please use this method to implement it in the right way:
String emailInput;
emailInput = textInputEmail.getEditText().getText();
if (emailInput != null) {
emailInput = emailInput.toString().trim();
}
Or (My favorite way)
String emailInput = "";
try {
emailInput = textInputEmail.getEditText().getText().toString().trim();
} catch (IllegalArgumentException ex) { }

error in android application ArrayList

Hello how are you? I'm creating an android app news and is working very well, the only problem is when I'm doing the reading of the text and minimize the app to do something else and then return the app presents this error.
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: FATAL EXCEPTION: main
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at java.util.ArrayList.get(ArrayList.java:304)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at com.brfgd.ActivityDetailStory.setAdapterToListview(ActivityDetailStory.java:179)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at com.brfgd.ActivityDetailStory$MyTask.onPostExecute(ActivityDetailStory.java:171)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at com.brfgd.ActivityDetailStory$MyTask.onPostExecute(ActivityDetailStory.java:119)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at android.os.AsyncTask.finish(AsyncTask.java:631)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at android.os.AsyncTask.access$600(AsyncTask.java:177)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:99)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at android.os.Looper.loop(Looper.java:153)
part of the error
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class ActivityDetailStory extends AppCompatActivity {
int position;
String str_cid, str_cat_id, str_cat_image, str_cat_name, str_title, str_image, str_desc, str_date;
TextView news_title, news_date;
WebView news_desc;
ImageView img_news, img_fav;
DatabaseHandler db;
List<ItemStoryList> arrayOfRingcatItem;
ItemStoryList objAllBean;
final Context context = this;
ProgressBar progressBar;
LinearLayout content;
private AdView mAdView;
private InterstitialAd interstitial;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_story);
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final android.support.v7.app.ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(Constant.CATEGORY_TITLE);
}
//show admob banner ad
mAdView = (AdView) findViewById(R.id.adView);
mAdView.loadAd(new AdRequest.Builder().build());
mAdView.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
}
#Override
public void onAdFailedToLoad(int error) {
mAdView.setVisibility(View.GONE);
}
#Override
public void onAdLeftApplication() {
}
#Override
public void onAdOpened() {
}
#Override
public void onAdLoaded() {
mAdView.setVisibility(View.VISIBLE);
}
});
content = (LinearLayout) findViewById(R.id.content);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
img_fav = (FloatingActionButton) findViewById(R.id.img_fav);
img_news = (ImageView) findViewById(R.id.image);
news_title = (TextView) findViewById(R.id.title);
news_date = (TextView) findViewById(R.id.subtitle);
news_desc = (WebView) findViewById(R.id.desc);
db = new DatabaseHandler(ActivityDetailStory.this);
arrayOfRingcatItem = new ArrayList<ItemStoryList>();
//imageLoader = new ImageLoader(ActivityDetailStory.this);
if (JsonUtils.isNetworkAvailable(ActivityDetailStory.this)) {
new MyTask().execute(Constant.SERVER_URL + "/api.php?nid=" + Constant.NEWS_ITEMID);
MyApplication.getInstance().trackScreenView("Lendo de cara : " + (Constant.CATEGORY_TITLE));
}
else {
Toast.makeText(getApplicationContext(), "Problema com sua Rede de Internet", Toast.LENGTH_SHORT).show();
}
}
private class MyTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... params) {
return JsonUtils.getJSONString(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressBar.setVisibility(View.GONE);
content.setVisibility(View.VISIBLE);
if (null == result || result.length() == 0) {
Toast.makeText(getApplicationContext(), "Problema com sua Rede de Internet!", Toast.LENGTH_SHORT).show();
} else {
try {
JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray = mainJson.getJSONArray(Constant.CATEGORY_ARRAY_NAME);
JSONObject objJson = null;
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
ItemStoryList objItem = new ItemStoryList();
objItem.setCId(objJson.getString(Constant.CATEGORY_ITEM_CID));
objItem.setCategoryName(objJson.getString(Constant.CATEGORY_ITEM_NAME));
objItem.setCategoryImage(objJson.getString(Constant.CATEGORY_ITEM_IMAGE));
objItem.setCatId(objJson.getString(Constant.CATEGORY_ITEM_CAT_ID));
objItem.setNewsImage(objJson.getString(Constant.CATEGORY_ITEM_NEWSIMAGE));
objItem.setNewsHeading(objJson.getString(Constant.CATEGORY_ITEM_NEWSHEADING));
objItem.setNewsDescription(objJson.getString(Constant.CATEGORY_ITEM_NEWSDESCRI));
objItem.setNewsDate(objJson.getString(Constant.CATEGORY_ITEM_NEWSDATE));
arrayOfRingcatItem.add(objItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
setAdapterToListview();
}
}
}
public void setAdapterToListview() {
//if(arrayOfRingcatItem.size()>0) {
objAllBean = arrayOfRingcatItem.get(0);
str_cid = objAllBean.getCId();
str_cat_name = objAllBean.getCategoryName();
str_cat_image = objAllBean.getCategoryImage();
str_cat_id = objAllBean.getCatId();
str_title = objAllBean.getNewsHeading();
str_desc = objAllBean.getNewsDescription();
str_image = objAllBean.getNewsImage();
str_date = objAllBean.getNewsDate();
news_title.setText(str_title);
news_date.setText(str_date);
news_desc.setBackgroundColor(Color.parseColor("#FFFFFF"));
news_desc.setFocusableInTouchMode(false);
news_desc.setFocusable(false);
news_desc.getSettings().setDefaultTextEncodingName("UTF-8");
WebSettings webSettings = news_desc.getSettings();
Resources res = getResources();
int fontSize = res.getInteger(R.integer.font_size);
webSettings.setDefaultFontSize(fontSize);
String mimeType = "text/html; charset=UTF-8";
String encoding = "utf-8";
String htmlText = str_desc;
String text = "<html><head><style type=\"text/css\">#font-face {font-family: MyFont;src: url(\"file:///android_asset/Roboto-Light.ttf\")}body {font-family: MyFont;font-size: medium; color: #525252;}</style></head><body>"
+ htmlText + "</body></html>";
news_desc.loadData(text, mimeType, encoding);
List<Pojo> pojolist = db.getFavRow(str_cat_id);
if (pojolist.size() == 0) {
img_fav.setImageResource(R.drawable.ic_bookmark_outline);
} else {
if (pojolist.get(0).getCatId().equals(str_cat_id))
;
{
img_fav.setImageResource(R.drawable.ic_bookmark_white);
}
}
img_fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
List<Pojo> pojolist = db.getFavRow(str_cat_id);
if (pojolist.size() == 0) {
db.AddtoFavorite(new Pojo(str_cat_id, str_cid, str_cat_name, str_title, str_image, str_desc, str_date));
Toast.makeText(getApplicationContext(), "Leitura Marcada", Toast.LENGTH_SHORT).show();
img_fav.setImageResource(R.drawable.ic_bookmark_white);
interstitial = new InterstitialAd(ActivityDetailStory.this);
interstitial.setAdUnitId(getString(R.string.admob_interstitial_id));
AdRequest adRequest = new AdRequest.Builder().build();
interstitial.loadAd(adRequest);
interstitial.setAdListener(new AdListener() {
public void onAdLoaded() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
});
} else {
if (pojolist.get(0).getCatId().equals(str_cat_id)) {
db.RemoveFav(new Pojo(str_cat_id));
Toast.makeText(getApplicationContext(), "Leitura desmarcada!", Toast.LENGTH_SHORT).show();
img_fav.setImageResource(R.drawable.ic_bookmark_outline);
}
}
}
});
//}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_story, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
case R.id.menu_share:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Estou lendo vários livro com esse app estou adorando, baixe já, Recomendo "+"https://play.google.com/store/apps/details?id="+getPackageName());
sendIntent.setType("text/plain");
startActivity(sendIntent);
break;
default:
return super.onOptionsItemSelected(menuItem);
}
return true;
}
#Override
protected void onPause() {
// mAdView.pause();
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
//mAdView.resume();
}
#Override
protected void onDestroy() {
//mAdView.destroy();
super.onDestroy();
}
}
You should do this:
public void setAdapterToListview() {
if(arrayOfRingcatItem.size>0){
objAllBean = arrayOfRingcatItem.get(0);
str_cid = objAllBean.getCId();
str_cat_name = objAllBean.getCategoryName();
}
}
EDIT: onResume()
#Override
protected void onResume(){
super.onResume();
arrayOfRingcatItem = new ArrayList<ItemStoryList>();
//imageLoader = new ImageLoader(ActivityDetailStory.this);
if (JsonUtils.isNetworkAvailable(ActivityDetailStory.this)) {
new MyTask().execute(Constant.SERVER_URL + "/api.php?nid=" + Constant.NEWS_ITEMID);
MyApplication.getInstance().trackScreenView("Lendo de cara : " + (Constant.CATEGORY_TITLE));
}
else {
Toast.makeText(getApplicationContext(), "Problema com sua Rede de Internet", Toast.LENGTH_SHORT).show();
}
}
Or you can save the array in the Application class and use it from there, or in a singleton. The error it's because when the activity go to background Android can release some memory and delete your array.
EDIT 2: You can use SharedPreferences to save the id.
You have to put this code in onCreate:
SharedPreferences opc=getSharedPreferences("AppName", 0);
SharedPreferences.Editor editor =opc.edit();
editor.putInt("ID_SAVED",NEWS_ITEMID); editor.commit();
And in the onResume:
SharedPreferences opc=getSharedPreferences("AppName", 0);
NEWS_ITEMID=opc.getInt("ID_SAVED", -1);
Based on what you stated above everything is working fine except:
minimize the app to do something else and then return the app presents this error
You may need to reinitialize code in:
#Override
public void onResume(){
super.onResume();
// put your code here to repopulate arraylist...
refreshMyData();
}
refreshMyData could have:
public void refreshMyData(){
if (JsonUtils.isNetworkAvailable(ActivityDetailStory.this)) {
new MyTask().execute(Constant.SERVER_URL + "/api.php?nid=" + Constant.NEWS_ITEMID);
MyApplication.getInstance().trackScreenView("Lendo de cara : " + (Constant.CATEGORY_TITLE));
}else {
Toast.makeText(getApplicationContext(), "Problema com sua Rede de Internet", Toast.LENGTH_SHORT).show();
}
}
Use this method in your oncreate as well, that way you can have the same method call when creating the activity and resuming.
Sources:
How to use onResume()?

EditText gives NullPointerException on getText

I'm kinda new and any help would be appreciated
Currently either it's filled it in or I'm getting a toast saying there is a nullpointer.
In the if else statement it will always jump to the else part. So the if doesn't seem to tihnk it's empty while that is what I'm getting in the toast(Created in the catch)
package com.example.domoticaapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class CreateProfile extends Activity implements OnClickListener
{
//Declare Variables
DBAdapter myDb;
EditText ipInput, nameInput;
Button save;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.create_profile);
ipInput = (EditText) findViewById(R.id.ipInput);
nameInput = (EditText) findViewById(R.id.nameInput);
save = (Button) findViewById(R.id.save);
save.setOnClickListener(this);
}
private void saveProfile()
{
String IP = ipInput.getText().toString();
String name = nameInput.getText().toString();
if(IP == null || name == null || IP == "" || name == "")
{
Toast.makeText(this, "Name and IP can't be empty!", Toast.LENGTH_SHORT).show();
}
else
{
try
{
myDb.insertRow(name, IP);
//Intent i = new Intent("com.example.domoticaapp.SQLView");
//startActivity(i);
}
catch(Exception e)
{
Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onClick(View v)
{
switch(v.getId())
{
case R.id.save:
saveProfile();
break;
}
}
}
Try this.
if(!IP.equals("") && !name.equals(""))
{
/** Your Code **/
}
else
{
Toast.makeText(this, "Name and IP can't be empty!", Toast.LENGTH_SHORT).show();
}
try this
if(TextUtils.isEmpty(name ) &&TextUtils.isEmpty(IP)){
Toast....
}else{
...
}
DBAdapter myDb;
myDb has not been intialised. You just declared it

Why doesn't this if statement work?

I'm trying to create an if statement, for example if the user doesn't type anything into the the two edit text's, then it displays a toast and resets everything. But for some reason, my code completely ignores this and just goes to the else statement instead.
Can anyone help?
My Code:
package com.gta5news.bananaphone;
import java.io.File;
import android.R.string;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LogIn extends Activity implements OnClickListener {
Button send;
EditText user;
EditText pass;
CheckBox staySignedIn;
SharedPreferences shareduser;
SharedPreferences sharedpass;
public static String settings = "MySharerdUser";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
send = (Button) findViewById(R.id.bLogIn);
user = (EditText) findViewById(R.id.eTuser);
pass = (EditText) findViewById(R.id.eTpassword);
staySignedIn = (CheckBox) findViewById(R.id.Cbstay);
send.setOnClickListener(this);
SharedPreferences settings = getPreferences(MODE_PRIVATE);
String name = settings.getString("name", "");
String password = settings.getString("pwd", "");
user.setText(name);
pass.setText(password);
if (staySignedIn.isChecked()) {
SharedPreferences MySharedUser = getPreferences(MODE_PRIVATE);
settings.edit().putString("name", user.getText().toString())
.putString("pwd", pass.getText().toString()).commit();
}
if (user.length() > 0)
;
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bLogIn:
if (user.length() < 0)
Toast.makeText(this,
"Try to type in your username and password again!",
Toast.LENGTH_LONG).show();
else {
String u = user.getText().toString();
String p = pass.getText().toString();
Bundle send = new Bundle();
send.putString("key", u);
send.putString("key", p);
Intent a = new Intent(LogIn.this, FTPClient.class);
startActivity(a);
Toast.makeText(this, "Yay, you signed in!", Toast.LENGTH_LONG)
.show();
break;
}
}
}
}
if (user.length() == 0)
try it because user.length() is never come in Less Than Zero
You have to use
user.getText().toString().length()
Do you need an onClickListener for you checkbox???
checkbox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks, depending on whether it's now checked
if (((CheckBox) v).isChecked()) {
Toast.makeText(HelloFormStuff.this, "Selected", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(HelloFormStuff.this, "Not selected", Toast.LENGTH_SHORT).show();
}
}
});

Categories