Problem when logging in using AnsycTask on android - java

I am using MySQL as a bank hosted on an AWS server
I use the AsyncTask class to login, doing the search with SELECT * from ... I check the search with ResultSet, the code executes quietly, but when I click the Login button, it goes into exception.
I use the same code to insert data into the database and it performs right
Only verification is not right
public class Tela_Login extends AppCompatActivity {
ConnectionClass connectionClass;
EditText editUsuario, editSenha;
Button btLogin;
TextView textCadastro;
ProgressBar pbbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tela__login);
ConnectionClass connectionClass;
editUsuario = (EditText) findViewById(R.id.editUsuario);
editSenha = (EditText) findViewById(R.id.editSenha);
textCadastro = (TextView) findViewById(R.id.textCadastro);
btLogin = (Button) findViewById(R.id.btLogin);
pbbar = (ProgressBar) findViewById(R.id.pbbar);
pbbar.setVisibility(View.GONE);
btLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
realizarLogin realizarLogin = new realizarLogin();
btLogin.setClickable(false);
realizarLogin.execute("");
}
});
}
public class realizarLogin extends AsyncTask<String,String,String>{
String z = "";
Boolean isSuccess = false;
#Override
protected void onPreExecute() {
pbbar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String r) {
pbbar.setVisibility(View.GONE);
Toast.makeText(Tela_Login.this, r, Toast.LENGTH_SHORT).show();
if (isSuccess) {
Toast.makeText(Tela_Login.this, r, Toast.LENGTH_SHORT).show();
}
}
#Override
protected String doInBackground(String... params) {
String usuario = editUsuario.getText().toString();
String senha = editSenha.getText().toString();
if (usuario.trim().equals("") || senha.trim().equals(""))
z = "Por favor os valores!";
else {
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Erro ao conectar no banco de dados";
} else {
String query = "select * from Salao where email='" +usuario+"' and senha='" +senha+"'";
Statement stmt = con.createStatement();
ResultSet rs;
rs = stmt.executeQuery(query);
if (rs.next()) {
z = "Login sucessful";
isSuccess = true;
} else {
z = "Invalid Credentials";
isSuccess = false;
}
}
} catch (Exception ex) {
isSuccess = false;
z = "Exceptions";
}
}
btLogin.setClickable(true);
return z;
}
}
}

Related

Unable to use boolean values in IF statements

I have a database that is being checked using a Cursor. This database compares the data in the database to the user entered username and password. If they match data in the database a boolean is returned true. I can use a toast to output the boolean which correctly outputs as true or false if the input data does or does not match.
However, i am trying to use the boolean to move to the next activity. If the boolean is true the next intent is started. This does not work for some reason and I cant seem to work out why. Any help would be great. Thanks!
public Button btnLogin, btnSignup;
public EditText UsernameInput, PasswordInput;
public DatabaseHelper db;
public static String passUser, passPass, passFirst, passSecond;
public int count;
public Boolean matchingUser = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Align page and remove notification bar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
// Define everything
btnLogin = findViewById(R.id.btnLogin);
btnSignup = findViewById(R.id.btnSignup);
UsernameInput = findViewById(R.id.UsernameInput);
PasswordInput = findViewById(R.id.PasswordInput);
db = new DatabaseHelper(this);
// validation button
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
validateLogin(UsernameInput.getText().toString(), PasswordInput.getText().toString());
}
});
btnSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CreateUser();
}
});
}
// Validation code
public void validateLogin(String userName, String userPassword)
{
if (userName.equals("")|| userPassword.equals(""))
{
Toast.makeText(getApplicationContext(),"Fields are empty",Toast.LENGTH_SHORT).show();
}
else
{
// CHECKING USER LOGIN DETAILS
Cursor cursor = db.CompareUserData();
for (count = 0; count<=cursor.getCount();count++)
{
if (cursor.moveToPosition(count))
{
if (UsernameInput.getText().toString().equals(cursor.getString(0))&&PasswordInput.getText().toString().equals(cursor.getString(1)))
{
matchingUser = true;
}
}
Toast.makeText(this, "boolean : "+ matchingUser, Toast.LENGTH_SHORT).show();
if (matchingUser = true)
{
passUser = cursor.getString(0);
passPass = cursor.getString(1);
passFirst = cursor.getString(2);
passSecond = cursor.getString(3);
getUser();
getPass();
getFirst();
getSecond();
Toast.makeText(getApplicationContext(), "Successfully logged in", Toast.LENGTH_SHORT).show();
LoginValidation();
}
if (matchingUser = false)
{
Toast.makeText(getApplicationContext(),"Incorrect Username",Toast.LENGTH_SHORT).show();
}}
}
}
private void LoginValidation()
{
// Changing activity code
startActivity(new Intent(MainActivity.this,Login_Biometrics.class));
}
private void CreateUser()
{
// Changing activity code
startActivity(new Intent(MainActivity.this,createUser.class));
}
public static String getUser ()
{
return passUser;
}
public static String getPass ()
{
return passPass;
}
public static String getFirst ()
{
return passFirst;
}
public static String getSecond ()
{
return passSecond;
}
It wont work with one = equal sign just do:
if(matchingUser) {
// if true do something
} else {
// if false do something
}
In your case:
if (matchingUser) {
passUser = cursor.getString(0);
passPass = cursor.getString(1);
passFirst = cursor.getString(2);
passSecond = cursor.getString(3);
getUser();
getPass();
getFirst();
getSecond();
Toast.makeText(getApplicationContext(), "Successfully logged in",Toast.LENGTH_SHORT).show();
LoginValidation();
} else {
Toast.makeText(getApplicationContext(),"Incorrect Username",Toast.LENGTH_SHORT).show();
}
You have to understand some basics:
Assignment operator =
Is used to assign value to some variable.
Logical operator ==
Is used to make some logical comparison.
So instead of doing this:
if (matchingUser = true)
{
...
Do this
if (matchingUser == true)
{
...
Apply this for every condition checking in your code.

The application may be doing too much work on its main thread. (android studio emulator and real phone emulator )

firstly, i read all answers related with this problem but i didn't solve this error. My program is running but very laggy and slow. i tryed use smaller images and use async task but my problem is continued. here is my code
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
NotificationManager manager;
public Veri veri,veri1;
int x= 0;
private Timer autoUpdate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
veri1 = new Veri();
x=veri1.getList().size();
recyclerView= (RecyclerView) findViewById(R.id.my_recycler_view);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
onResume();
new AsyncCaller().execute();
}
#Override
protected void onStart() {
super.onStart();
}
////////////////////////////////////////////
private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
autoUpdate = new Timer();
autoUpdate.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
updateHTML();
}
});
}
}, 0, 60000);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
////////////////////////////////////
private void updateHTML(){
// your logic here
RecyclerAdapter adapter=new RecyclerAdapter(this);
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
veri = new Veri();
int a = veri.getList().size();
if(a!=x){
generateNotification(MainActivity.this,"Listede Degisim Var");
}
x=a;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
// search action
case R.id.action_location_found:
// location found
LocationFound();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void LocationFound() {
Intent i = new Intent(MainActivity.this, LocationFound.class);
startActivity(i);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main_actions, menu);
return super.onCreateOptionsMenu(menu);
}
private void generateNotification(Context context,String message){
int notificationId = 001;
Intent viewIntent = new Intent(context, MainActivity.class);
PendingIntent viewPendingIntent =
PendingIntent.getActivity(context, 0, viewIntent, 0);
NotificationCompat.Builder notificationBuilder =
(NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.dikat)
.setContentTitle("Bildirim")
.setContentText(message)
.setContentIntent(viewPendingIntent)
.setAutoCancel(true)
.setSound(Uri.parse("android.resource://"
+ context.getPackageName() + "/" + R.raw.bildirim))
.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(context);
notificationManager.notify(notificationId, notificationBuilder.build());
}
}
here is my data class
public class Veri extends ActionBarActivity {
NotificationManager manager;
Notification myNotication;
String ip, db, un, passwords;
Connection connect,conn;
PreparedStatement stmt;
ResultSet rs;
TextView tv;
int position1=0;
Button b1;
ArrayList<String> data = new ArrayList<String>();
ArrayList<String> data2 = new ArrayList<String>();
public Veri(){
ip = "x.x.x.x";
un = "x";
passwords = "x";
db = "xxx";
connect = CONN(un, passwords, db, ip);
String query = "SELECT Adsoyad,(DATEPART(hour, BeklemeSuresi) * 3600) + (DATEPART(minute, BeklemeSuresi) * 60) + DATEPART(second, BeklemeSuresi) as SecondsFromMidnight,Durum FROM [dbo].[IslemiDevamEdenHasta] (1)";
try {
// connect = CONN(un, passwords, db, ip);
stmt = connect.prepareStatement(query);
rs = stmt.executeQuery();
while (rs.next()) {
int b = (int)rs.getInt("SecondsFromMidnight")/60;
if(b>50) {
String id = rs.getString("Adsoyad");
String id2 = rs.getString("Durum");
String full = id + " " + id2;
String a = "" + b;
data.add(full);
data2.add(a);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public ArrayList<String> getList() {
return data;
}
public ArrayList<String> getList2() {
return data2;
}
#SuppressLint("NewApi")
private Connection CONN(String _user, String _pass, String _DB,
String _server) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn = null;
String ConnURL = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
ConnURL = "jdbc:jtds:sqlserver://" + _server + ";"
+ "databaseName=" + _DB + ";user=" + _user + ";password="
+ _pass + ";";
conn = DriverManager.getConnection(ConnURL);
} catch (SQLException se) {
Log.e("ERRO", se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("ERRO", e.getMessage());
} catch (Exception e) {
Log.e("ERRO", e.getMessage());
}
return conn;
}
}
and here is my recycler class
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerViewHolder> {
public Veri veri = new Veri();
int sayi=0;
ArrayList<String> liste = veri.getList();
ArrayList<String> liste2 = veri.getList2();
static ArrayList<String> liste3 = new ArrayList<String>() ;
Context context;
LayoutInflater inflater;
public RecyclerAdapter(Context context) {
this.context=context;
inflater=LayoutInflater.from(context);
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v=inflater.inflate(R.layout.item_list, parent, false);
RecyclerViewHolder viewHolder=new RecyclerViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
liste3.add("a");
sayi = 0;
for (int j = 0; j < liste3.size(); j++) {
if (liste3.get(j).equals(liste.get(position))) {
sayi++;
}
if (sayi == 0) {
holder.tv1.setText(liste.get(position));
holder.tv2.setText(liste2.get(position));
holder.imageView.setOnClickListener(clickListener);
holder.imageView.setTag(holder);
} else {
holder.tv1.setText(liste.get(position));
holder.tv2.setText(liste2.get(position));
holder.imageView.setOnClickListener(clickListener);
holder.imageView.setImageResource(R.drawable.ic_checkin);
}
}
}
View.OnClickListener clickListener=new View.OnClickListener() {
#Override
public void onClick(View v) {
RecyclerViewHolder vholder = (RecyclerViewHolder) v.getTag();
int position = vholder.getPosition();
//Toast.makeText(context,"This is position "+position,Toast.LENGTH_LONG ).show();
vholder.imageView.setImageResource(R.drawable.ic_checkin);
liste3.add(liste.get(position));
}
};
#Override
public int getItemCount() {
return liste.size();
}
}
what is my problem??
you doing so much coding for loading image.There are some third party api so you can refer it. so it may be helpful to load your image easily and memory management control is handle by that api also here just refer this tutorial.

How do I pass a variable from an activity to a fragment?

I have tried using the code below but it does not work. it just returns a null value when retrieved from the fragment.
MainActivity.java
setting the bundle:
public class MainActivity extends Activity {
ConnectionClass connectionClass;
EditText edtuserid,edtpass;
Button btnlogin;
ProgressBar pbbar;
int user_id;
int lala;
int test2;
String userIDD;
String user_fname;
String user_lname;
int dept_id;
String test;
String user_email;
String user_password;
String user_username;
Bundle profileBundle;
String userid;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectionClass = new ConnectionClass();
edtuserid = (EditText) findViewById(R.id.edtuserid);
edtpass = (EditText) findViewById(R.id.edtpass);
btnlogin = (Button) findViewById(R.id.btnlogin);
pbbar = (ProgressBar) findViewById(R.id.pbbar);
pbbar.setVisibility(View.GONE);
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
userid = edtuserid.getText().toString();
password = edtpass.getText().toString();
int lala = Integer.parseInt(userid);
test2 = lala;
DoLogin doLogin = new DoLogin();
doLogin.execute("");
}
});
}
public class DoLogin extends AsyncTask<String,String,String>
{
String z = "";
Boolean isSuccess = false;
#Override
protected void onPreExecute() {
pbbar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String r) {
pbbar.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, r, Toast.LENGTH_SHORT).show();
if(isSuccess) {
//DITO ANG REDIRECTION
Intent base = new Intent(MainActivity.this, OtherActivity.class);
startActivity(base);
finish();
}
}
#Override
public String doInBackground(String... params) {
if(userid.trim().equals("")|| password.trim().equals(""))
z = "Please enter User Id and Password";
else
{
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
String query = "select user_id, user_fname, user_lname,department_id, user_email, user_password, user_username from users where user_id='" + userid + "' and user_password='" + password + "'";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs.next())
{
userIDD = rs.getString(1);
user_fname = rs.getString(2);
user_lname = rs.getString(3);
dept_id = rs.getInt(4);
user_email = rs.getString(5);
user_password = rs.getString(6);
user_username = rs.getString(7);
profileBundle = new Bundle();
profileBundle.putInt("userID", user_id);
profileBundle.putInt("deptID", dept_id);
profileBundle.putString("fname", user_fname);
profileBundle.putString("lname", user_lname);
profileBundle.putString("email", user_email);
profileBundle.putString("pass", user_password);
Fragment fragobj=new PathfinderAdd();
fragobj.setArguments(profileBundle);
//Fragment fragobj = new PathfinderAdd();
//fragobj.setArguments(profileBundle);
z = "Logged In as: " + user_username;
isSuccess=true;
}
else
{
z = "Invalid Credentials";
isSuccess = false;
}
}
}
catch (Exception ex)
{
isSuccess = false;
Log.e("MYAPP", "exception", ex);
z = "Error Somewhere";
}
}
return z;
}
}
public int getMyData() {
int wa = lala;
return wa;
}
}
PahtfinderAdd.java
getting the bundle in the fragment
public class PathfinderAdd extends Fragment {
ConnectionClass connectionClass;
EditText edtideaname, edtbenefit,edtobservation,edtquickwin,targetdate;
Button btnadd;
TextView targettv;
Spinner spinner1, spinner2;
ProgressBar pbbar;
String proid;
CalendarView calendar;
String realDate;
String DAY;
Date targ = null;
String finalDate;
SimpleDateFormat timeFormat;
java.sql.Date sql;
Date date2;
Integer userID;
int user;
public PathfinderAdd(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.addpathfinder, container, false);
connectionClass = new ConnectionClass();
edtideaname = (EditText) rootView.findViewById(R.id.edtideaname);
edtbenefit = (EditText) rootView.findViewById(R.id.edtbenefit);
edtobservation = (EditText) rootView.findViewById(R.id.edyobservation);
edtquickwin = (EditText) rootView.findViewById(R.id.edtquickwin);
targetdate = (EditText) rootView.findViewById(R.id.target);
spinner1 = (Spinner) rootView.findViewById(R.id.spinner1);
spinner2 = (Spinner) rootView.findViewById(R.id.spinner2);
btnadd = (Button) rootView.findViewById(R.id.btnadd);
pbbar = (ProgressBar) rootView.findViewById(R.id.pbbar);
targettv = (TextView) rootView.findViewById(R.id.tvtarget);
pbbar.setVisibility(View.GONE);
calendar = (CalendarView) rootView.findViewById(R.id.calendar1);
proid = "";
userID = getArguments().getInt("userID");
Bundle bundle = this.getArguments();
user = bundle.getInt("userID");
//String lol = new getMyData().
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddPro addPro = new AddPro();
addPro.execute("");
}
});
calendar.setOnDateChangeListener(new OnDateChangeListener() {
public void onSelectedDayChange(CalendarView view, int year_date, int month_date,
int dayOfMonth) {
int day = dayOfMonth;
int month = month_date;
int year = year_date;
DAY=String.valueOf(year)+String.valueOf(month)+String.valueOf(day);
}
});
return rootView;
}
public class AddPro extends AsyncTask<String, String, String> {
String z = "";
Boolean isSuccess = false;
String observation = edtobservation.getText().toString();
String quickwin = edtquickwin.getText().toString();
String ideaname = edtideaname.getText().toString();
String benefit = edtbenefit.getText().toString();
String target_date = targetdate.getText().toString();
String process = spinner1.getSelectedItem().toString();
String benefitType = spinner2.getSelectedItem().toString();
String lol = "2015-11-28";
Integer benefit_type = spinner2.getSelectedItemPosition();
Integer idea_type = spinner1.getSelectedItemPosition();
Integer idea_id;
Integer benefit_id;
Integer pathfinder_id = 1;
Integer pathfinder_status = 9;
Integer pathfinder_prog = 0;
#Override
protected void onPreExecute() {
pbbar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String r) {
pbbar.setVisibility(View.GONE);
Toast.makeText(PathfinderAdd.this.getActivity(), r, Toast.LENGTH_SHORT).show();
if(isSuccess==true) {
edtideaname.setText(null);
edtbenefit.setText(null);
edtobservation.setText(null);
edtquickwin.setText(null);
targetdate.setText(null);
}
}
#Override
protected String doInBackground(String... params) {
if (ideaname.trim().equals("") || benefit.isEmpty() || observation.trim().equals("") || quickwin.trim().equals(""))
z = "Please fill all the fields";
else {
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
//timeFormat = new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH);
//finalDate = timeFormat.format(targ);
//sql = new java.sql.Date(targ.getTime());
int lol=1;
double benefitInt = Double.parseDouble(benefit);
date2 = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH).parse(DAY);
String newDateString = new SimpleDateFormat("yyyy/MM/dd",Locale.ENGLISH).format(date2);
DateFormat format2 = new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH);
Date date3 = format2.parse(newDateString);
java.sql.Date finalDt = new java.sql.Date(date3.getTime());
String dates = new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH)
.format(Calendar.getInstance().getTime());
//String date = new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH)
//.format(calendar.getDate());
switch (idea_type)
{
case 0:
idea_id = 1;
break;
case 1:
idea_id = 2;
break;
case 2:
idea_id = 3;
break;
case 3:
idea_id = 4;
break;
case 4:
idea_id = 5;
break;
default:
idea_id = 1;
break;
}
switch(benefit_type)
{
case 0:
benefit_id = 1;
break;
case 1:
benefit_id = 2;
break;
default:
benefit_id = 1;
break;
}
String query = "insert into pathfinder (pathfinder_id,pathfinder_name,idea_id,benefit_id,pathfinder_potential_eqv,pathfinder_observation,pathfinder_quickwin,pathfinder_target_closure,pathfinder_status,pathfinder_progress,patfinder_actual_closure,pathfinder_date_raised,user_id)" +
"values ('" +pathfinder_id+ "','" +ideaname+ "','" +idea_id+ "','" +benefit_id+ "','" +benefitInt+ "','" +observation+ "','" +quickwin+ "','" +dates+ "','" +pathfinder_status+ "','" +pathfinder_prog+ "','" +dates+ "','" +dates+ "','" + user+"')";
PreparedStatement preparedStatement = con.prepareStatement(query);
preparedStatement.executeUpdate();
z = "Added Successfully";
isSuccess = true;
}
} catch (Exception ex) {
isSuccess = false;
z = "Exceptions";
Log.e("MYAPP", "exception", ex);
}
}
return z;
}
}
}
You can add or replace Fragment by calling this in your activity
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
more Fragment information check this http://developer.android.com/guide/components/fragments.html
To get data from you activity you can create a method in your activity
public dataType getData() {
return data;
}
in your fragment, you can get data by calling
((YourActivityClass) getActivity()).getData();
Hope this help!!
You are setting the Bundle to the Fragment, but where are you replacing/adding the Fragment? I can't see any FragmentTransaction.
Here you have some examples: http://developer.android.com/reference/android/app/Fragment.html
"DetailsActivity" is what you need, if I'm not wrong.
Example:
When you want to start your Fragment from the Activity:
Fragment fragobj=new PathfinderAdd();
fragobj.setArguments(profileBundle);
getFragmentManager().beginTransaction().add(android.R.id.content, fragobj).commit();
Where android.R.id.content is the container for your Fragments. When you do this your Fragment will be shown and the Bundle will be received.
In your Fragment "onCreate":
if (getArguments() != null) {
Bundle bundle = this.getArguments();
user = bundle.getInt("userID");
}

Connection ... or invalid mmi code android studio

My application consists of a listview that contains data retrieved from a database. The database has columns : cognome, nome, ruolo, telefono.
When I click on an item, a dialog containing 2 buttons is opened : call and sms.
I would like that when I click the button call, I hand the call to the number corresponding to the line.
The problem is when I click the button, there is an error message : >connection problem or invalid mmi code.
My main is below.
public class ListaContatti extends ListActivity {
PersonaManager manager;
List<Persona> lista = new ArrayList<>();
TextView visualizza;
private PersonaHelper mPersonaHelper;
private static final String TAG = "MyActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_contatti);
mPersonaHelper = new PersonaHelper(this);
manager = new PersonaManager(this);
manager.open();
visualizzaLista();
//stampaCose();
manager.close();
final ArrayAdapter<Persona> adapter = new ArrayAdapter<>(this, R.layout.row, R.id.textViewList, lista.toArray(new Persona[0]));
setListAdapter(adapter);
}
protected void onListItemClick(ListView list, View v, int position, long id) {
final Dialog dialog = new Dialog(this);
dialog.setTitle("Continua con ");
dialog.setContentView(R.layout.custom_dialog_layout);
TextView view = (TextView)findViewById(R.id.textViewList);
final Button call = (Button) dialog.findViewById(R.id.call);
Button sms = (Button) dialog.findViewById(R.id.sms);
//Button social = (Button) dialog.findViewById(R.id.social);
// add PhoneStateListener
PhoneCallListener phoneListener = new PhoneCallListener();
TelephonyManager telephonyManager = (TelephonyManager) this
.getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
SQLiteDatabase db = mPersonaHelper.getReadableDatabase();
final Cursor cursor = db.rawQuery("SELECT TELEFONO FROM contatti", null);
call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
cursor.moveToFirst();
final int numeroTelefono = cursor.getColumnIndex(PersonaHelper.TELEFONO);
while (cursor.isAfterLast() == false) {
//view.append("n" + cursor.getString(numeroTelefono));
cursor.moveToNext();
}
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + numeroTelefono ));
//callIntent.setData(Uri.parse("tel" + db.query("contatti", new String[]{"TELEFONO"}, null, null, null, null, null)));
startActivity(callIntent);
}
});
sms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "default content");
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
dialog.show();
}
private void stampaCose() {
StringBuilder sb = new StringBuilder();
for (Persona attuale : lista) {
sb.append(attuale.toString());
sb.append("\n");
}
}
private void visualizzaLista() {
Cursor cursor = manager.getPersoneSalvate();
lista.clear();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
String cognome = cursor.getString(cursor.getColumnIndex(PersonaHelper.COGNOME));
String nome = cursor.getString(cursor.getColumnIndex(PersonaHelper.NOME));
String ruolo = cursor.getString(cursor.getColumnIndex(PersonaHelper.RUOLO));
String numero = cursor.getString(cursor.getColumnIndex(PersonaHelper.TELEFONO));
//String mail = cursor.getString(cursor.getColumnIndex(PersonaHelper.COLUMN_MAIL));
// String descrizione = cursor.getString(cursor.getColumnIndex(PersonaHelper.COLUMN_DESCRIZIONE));
//lista.add(new Persona(cognome,nome, numero, mail)); // al posto dei due null mettere mail e descrizione
lista.add(new Persona(cognome, nome, ruolo, numero));
cursor.moveToNext();
}
}
//monitor phone call activities
private class PhoneCallListener extends PhoneStateListener {
private boolean isPhoneCalling = false;
String LOG_TAG = "LOGGING 123";
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (TelephonyManager.CALL_STATE_RINGING == state) {
// phone ringing
Log.i(LOG_TAG, "RINGING, number: " + incomingNumber);
}
if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
// active
Log.i(LOG_TAG, "OFFHOOK");
isPhoneCalling = true;
}
if (TelephonyManager.CALL_STATE_IDLE == state) {
// run when class initial and phone call ended,
// need detect flag from CALL_STATE_OFFHOOK
Log.i(LOG_TAG, "IDLE");
if (isPhoneCalling) {
Log.i(LOG_TAG, "restart app");
// restart app
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage(
getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
isPhoneCalling = false;
}
}
}
}
}

How to pass checkbox values to an ACTION_SEND

I'm trying to do my first app, I'm self-taught in Java and I started 2 month ago so please forgive my errors.
I want to pass the CheckBoxes values to an email text but I think I need to refresh "something" before sending the email because the values are always false..and I don't know how can I do.
Here is the code:
public class Appuntamento extends Activity{
String paziente;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.appuntamento);
//riceviamo id e lo mettiamo come nome utente
final EditText nomePaziente = (EditText)findViewById(R.id.nomePaziente);
Bundle dati = this.getIntent().getExtras();
nomePaziente.setText(dati.getString("id"));
final String id = dati.getString("id");
EditText noteAppuntamento = (EditText)findViewById(R.id.noteAppuntamento);
final String note = noteAppuntamento.getText().toString();
final CheckBox lunedi = (CheckBox) findViewById(R.id.checkboxLunedi);
final boolean lun = lunedi.isSelected();
final CheckBox martedi = (CheckBox) findViewById(R.id.checkboxMartedì);
final boolean mar = martedi.isSelected();
final CheckBox mercoledi = (CheckBox) findViewById(R.id.checkboxMercoledi);
final boolean mer = mercoledi.isSelected();
final CheckBox giovedi = (CheckBox) findViewById(R.id.checkboxGiovedi);
final boolean giov = giovedi.isSelected();
final CheckBox venerdi = (CheckBox) findViewById(R.id.checkboxVenerdi);
final boolean ven = venerdi.isSelected();
StringBuilder testoMail = new StringBuilder();
if (lun ){
testoMail.append("Lunedì");
} else if (mar){
testoMail.append("Martedì");
}else if (mer) {
testoMail.append("Mercoledì");
} else if (giov) {
testoMail.append("Giovedì");
} else if (ven) {
testoMail.append("Venerdì");
}
final String giorni = testoMail.toString();
Button richiestaAppuntamento = (Button)findViewById(R.id.btnRichiestaAppuntamento);
richiestaAppuntamento.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mail = new Intent(Intent.ACTION_SEND);
mail.setType("message/rfc822");
mail.putExtra(Intent.EXTRA_SUBJECT, "Richiesta appuntamento");
mail.putExtra(Intent.EXTRA_TEXT, "Nome paziente: " + id + " " + giorni + " " + "Note: " + note);
mail.putExtra(Intent.EXTRA_EMAIL, new String[] {"dottcastellitto#gmail.com"});
startActivity(mail);
}
});
}
}
two way you can do this one
like
public class Appuntamento extends Activity
{
String paziente;
boolean lun,mar ,mer,giov,ven;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.appuntamento);
//riceviamo id e lo mettiamo come nome utente
final EditText nomePaziente = (EditText)findViewById(R.id.nomePaziente);
Bundle dati = this.getIntent().getExtras();
nomePaziente.setText(dati.getString("id"));
final String id = dati.getString("id");
EditText noteAppuntamento = (EditText)findViewById(R.id.noteAppuntamento);
final String note = noteAppuntamento.getText().toString();
final CheckBox lunedi = (CheckBox) findViewById(R.id.checkboxLunedi);
final CheckBox martedi = (CheckBox) findViewById(R.id.checkboxMartedì);
final CheckBox mercoledi =(CheckBox)findViewById(R.id.checkboxMercoledi);
final CheckBox giovedi = (CheckBox) findViewById(R.id.checkboxGiovedi);
final CheckBox venerdi = (CheckBox) findViewById(R.id.checkboxVenerdi);
Button richiestaAppuntamento = (Button) findViewById(R.id.btnRichiestaAppuntamento);
richiestaAppuntamento.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ven = venerdi.isChecked();
lun = lunedi.isChecked();
mar = martedi.isChecked();
mer = mercoledi.isChecked();
giov = giovedi.isChecked();
StringBuilder testoMail = new StringBuilder();
//your code this is fine if only one selected item info or data you want to send in mail
if (lun ){
testoMail.append("Lunedì");
} else if (mar){
testoMail.append("Martedì");
}else if (mer) {
testoMail.append("Mercoledì");
} else if (giov) {
testoMail.append("Giovedì");
} else if (ven) {
testoMail.append("Venerdì");
}
// if you want all then comment above code and uncomment below code
/*
if (lun ){
testoMail.append("Lunedì");
}
if (mar){
testoMail.append("Martedì");
}
if (mer) {
testoMail.append("Mercoledì");
}
if (giov) {
testoMail.append("Giovedì");
}
if (ven) {
testoMail.append("Venerdì");
}
*/
String giorni = testoMail.toString();
Intent mail = new Intent(Intent.ACTION_SEND);
mail.setType("message/rfc822");
mail.putExtra(Intent.EXTRA_SUBJECT, "Richiesta appuntamento");
mail.putExtra(Intent.EXTRA_TEXT, "Nome paziente: " + id + " " + giorni + " " + "Note: " + note);
mail.putExtra(Intent.EXTRA_EMAIL, new String[] {"dottcastellitto#gmail.com"});
startActivity(mail);
}
});
}
}
other way is
like
public class Appuntamento extends Activity
{
String paziente;
boolean lun,mar ,mer,giov,ven;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.appuntamento);
//riceviamo id e lo mettiamo come nome utente
final EditText nomePaziente = (EditText)findViewById(R.id.nomePaziente);
Bundle dati = this.getIntent().getExtras();
nomePaziente.setText(dati.getString("id"));
final String id = dati.getString("id");
EditText noteAppuntamento = (EditText)findViewById(R.id.noteAppuntamento);
final String note = noteAppuntamento.getText().toString();
final CheckBox lunedi = (CheckBox) findViewById(R.id.checkboxLunedi);
lunedi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
lun=isChecked;
//either one above or below
//lun = lunedi.isChecked();
}
}
);
final CheckBox martedi = (CheckBox) findViewById(R.id.checkboxMartedì);
martedi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
mar=isChecked;
//either one above or below
//mar = martedi.isChecked();
}
}
);
final CheckBox mercoledi =(CheckBox)findViewById(R.id.checkboxMercoledi);
mercoledi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
mer=isChecked;
//either one above or below
// mer = mercoledi.isChecked();
}
}
);
final CheckBox giovedi = (CheckBox) findViewById(R.id.checkboxGiovedi);
giovedi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
giov=isChecked;
//either one above or below
// giov = giovedi.isChecked();
}
}
);
final CheckBox venerdi = (CheckBox) findViewById(R.id.checkboxVenerdi);
venerdi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
ven=isChecked;
//either one above or below
//ven = venerdi.isChecked();
}
}
);
Button richiestaAppuntamento = (Button) findViewById(R.id.btnRichiestaAppuntamento);
richiestaAppuntamento.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// ven = venerdi.isChecked();
// lun = lunedi.isChecked();
// mar = martedi.isChecked();
// mer = mercoledi.isChecked();
// giov = giovedi.isChecked();
StringBuilder testoMail = new StringBuilder();
//your code this is fine if only one selected item info or data you want to send in mail
if (lun ){
testoMail.append("Lunedì");
} else if (mar){
testoMail.append("Martedì");
}else if (mer) {
testoMail.append("Mercoledì");
} else if (giov) {
testoMail.append("Giovedì");
} else if (ven) {
testoMail.append("Venerdì");
}
// if you want all then comment above code and uncomment below code
/*
if (lun ){
testoMail.append("Lunedì");
}
if (mar){
testoMail.append("Martedì");
}
if (mer) {
testoMail.append("Mercoledì");
}
if (giov) {
testoMail.append("Giovedì");
}
if (ven) {
testoMail.append("Venerdì");
}
*/
String giorni = testoMail.toString();
Intent mail = new Intent(Intent.ACTION_SEND);
mail.setType("message/rfc822");
mail.putExtra(Intent.EXTRA_SUBJECT, "Richiesta appuntamento");
mail.putExtra(Intent.EXTRA_TEXT, "Nome paziente: " + id + " " + giorni + " " + "Note: " + note);
mail.putExtra(Intent.EXTRA_EMAIL, new String[] {"dottcastellitto#gmail.com"});
startActivity(mail);
}
});
}
}

Categories