Android Program crashes before even opening - android

I'm just starting to use Android Studio and allready having trouble, I need to conect to a database on sqlserver via my cellphone, but it crashes before the whole thing starts to work, I need a little help please, here is the code:
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
public class Farmaciapp extends AppCompatActivity {
EditText edtMed =(EditText)findViewById(R.id.edtMedicamento);
String ConsulMed = edtMed.getText().toString();
public void Meds (View v){
Connection conexion = null;
String url = "jdbc:jtds:sqlserver://192.168.1.69;databaseName=Medicamentos;";
String query = "Select Descripcion from Medicina where Nombre = '" + ConsulMed + "'";
try {
Connection con = DriverManager.getConnection(url);
Statement state = con.createStatement();
ResultSet resultado = state.executeQuery(query);
while (resultado.next()){
String res = resultado.getString(1);
TextView Explicacion = (TextView) findViewById(R.id.mltExplic);
Explicacion.setText(res);
}
}catch (Exception e){
Toast.makeText(getApplicationContext(), e.getMessage() , Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_farmaciapp);
}
}

The reason is you are trying to access which haven't yet created. Or in another word we can't reference or call findViewById until the layout is inflated.
so make below changes
public class Farmaciapp extends AppCompatActivity {
EditText edtMed;
String ConsulMed = edtMed.getText().toString();
public void Meds (View v){
Connection conexion = null;
String url = "jdbc:jtds:sqlserver://192.168.1.69;databaseName=Medicamentos;";
String query = "Select Descripcion from Medicina where Nombre = '" + ConsulMed + "'";
try {
Connection con = DriverManager.getConnection(url);
Statement state = con.createStatement();
ResultSet resultado = state.executeQuery(query);
while (resultado.next()){
String res = resultado.getString(1);
TextView Explicacion = (TextView) findViewById(R.id.mltExplic);
Explicacion.setText(res);
}
}catch (Exception e){
Toast.makeText(getApplicationContext(), e.getMessage() , Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_farmaciapp);
edtMed =(EditText)findViewById(R.id.edtMedicamento);
}
}
make sure to access edtMed after onCreate not before that will work. onCreate() is the way for activity to inflate the layout.

You need to Do findViewById inside onCreate() method
Declare your EditText edtMed as global
EditText edtMed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_farmaciapp);
edtMed =(EditText)findViewById(R.id.edtMedicamento);
}
Also get text from your EditText inside Meds (View v)
public void Meds (View v){
String ConsulMed = edtMed.getText().toString();
Connection conexion = null;
String url = "jdbc:jtds:sqlserver://192.168.1.69;databaseName=Medicamentos;";
String query = "Select Descripcion from Medicina where Nombre = '" + ConsulMed + "'";
try {
Connection con = DriverManager.getConnection(url);
Statement state = con.createStatement();
ResultSet resultado = state.executeQuery(query);
while (resultado.next()){
String res = resultado.getString(1);
TextView Explicacion = (TextView) findViewById(R.id.mltExplic);
Explicacion.setText(res);
}
}catch (Exception e){
Toast.makeText(getApplicationContext(), e.getMessage() , Toast.LENGTH_SHORT).show();
}
}

Related

unabel to connect to ms server 2017

When ever I click on the login button it always shows me check ur internet toast I don't know why I have also turned off my firewall also please help
I have also passed the internet permission also in the manifest .
Can someone also share the link from where I can learn how to pass values in android from sql server
thanks in advance !
MainActivity.java
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MainActivity extends AppCompatActivity
{
// Declaring layout button, edit texts
Button login;
EditText username,password;
ProgressBar progressBar;
// End Declaring layout button, edit texts
// Declaring connection variables
Connection con;
String un,pass,db,ip;
//End Declaring connection variables
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting values from button, texts and progress bar
login = (Button) findViewById(R.id.button);
username = (EditText) findViewById(R.id.editText);
password = (EditText) findViewById(R.id.editText2);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
// End Getting values from button, texts and progress bar
// Declaring Server ip, username, database name and password
ip = "LAPTOP-KOS272HK";
db = "fmv";
un = "username";
pass = "password";
// Declaring Server ip, username, database name and password
// Setting up the function when button login is clicked
login.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
CheckLogin checkLogin = new CheckLogin();// this is the Asynctask, which is used to process in background to reduce load on app process
checkLogin.execute("");
}
});
//End Setting up the function when button login is clicked
}
public class CheckLogin extends AsyncTask<String,String,String>
{
String z = "";
Boolean isSuccess = false;
#Override
protected void onPreExecute()
{
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String r)
{
progressBar.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, r, Toast.LENGTH_SHORT).show();
if(isSuccess)
{
Toast.makeText(MainActivity.this , "Login Successfull" , Toast.LENGTH_LONG).show();
//finish();
}
}
#Override
protected String doInBackground(String... params)
{
String usernam = username.getText().toString();
String passwordd = password.getText().toString();
if(usernam.trim().equals("")|| passwordd.trim().equals(""))
z = "Please enter Username and Password";
else
{
try
{
con = connectionclass(un, pass, db, ip); // Connect to database
if (con == null)
{
z = "Check Your Internet Access!";
}
else
{
// Change below query according to your own database.
String query = "select * from login where user_name= '" + usernam.toString() + "' and pass_word = '"+ passwordd.toString() +"' ";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs.next())
{
z = "Login successful";
isSuccess=true;
con.close();
}
else
{
z = "Invalid Credentials!";
isSuccess = false;
}
}
}
catch (Exception ex)
{
isSuccess = false;
z = ex.getMessage();
}
}
return z;
}
}
#SuppressLint("NewApi")
public Connection connectionclass(String user, String password, String database, String server)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection connection = null;
String ConnectionURL = null;
try
{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
ConnectionURL = "jdbc:jtds:sqlserver://" + server + database + ";user=" + user+ ";password=" + password + ";";
connection = DriverManager.getConnection(ConnectionURL);
}
catch (SQLException se)
{
Log.e("error here 1 : ", se.getMessage());
}
catch (ClassNotFoundException e)
{
Log.e("error here 2 : ", e.getMessage());
}
catch (Exception e)
{
Log.e("error here 3 : ", e.getMessage());
}
return connection;
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tanis.logi">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>

BufferedReader is not reading the file

I have this code in android studio for an app, I am trying to read from a file for the information of the login but anything after BufferedReader is not executing.
both the registration and login page open, the first page in the app i have sa login button and a registration button, when i click on the login button nothng happen, not even checking if the user exist or not
I tried many ways for reading and writing to a file but I couldn't figure out the error
it is not reading anything and not writing any thing, it simply does nothing.
this is the login page
package com.example.admin.projectfinal;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.admin.projectfinal.val.inputValidation;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class LoginActivity extends AppCompatActivity {
private inputValidation InputValidation;
private TextInputLayout IDLayout;
private TextInputLayout PASSWORDlayout;
private TextInputEditText LogID;
private TextInputEditText PASS;
Button SI;
TextView TV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getSupportActionBar().hide();
PASS = findViewById(R.id.password);
LogID = findViewById(R.id.idd);
IDLayout = findViewById(R.id.IDLayout);
PASSWORDlayout = findViewById(R.id.PasswordLayout);
TV = findViewById(R.id.tv);
SI = findViewById(R.id.signin);
SI.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();
}
});
TV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Navigate to RegisterActivity
Toast.makeText(LoginActivity.this, "we are in tv.", Toast.LENGTH_LONG).show();
Intent intentRegister = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intentRegister);
}
});
InputValidation = new inputValidation(LoginActivity.this);
}
private void login() {
if (!InputValidation.isInputEditTextFilled(LogID, IDLayout, "ID not filled ")) return;
if (!InputValidation.isInputEditTextFilled(PASS, PASSWORDlayout, "Password not filled"))
return;
TextView FileContentTextView = findViewById(R.id.tv_file_content);
try {
File f = new File ("User.txt");
BufferedReader reader = new BufferedReader(new FileReader(f));
if (reader.ready()) {
FileContentTextView.setText("No User registered");
return;
} else {
Toast.makeText(LoginActivity.this, "else", Toast.LENGTH_LONG).show();
boolean found = false;
String role = null;
String line;
while ((line = reader.readLine()) != null) {
Toast.makeText(LoginActivity.this, "while", Toast.LENGTH_LONG).show();
StringTokenizer user = new StringTokenizer(line);
String name = user.nextToken();
String Id = user.nextToken();
String dob = user.nextToken();
String pas = user.nextToken();
String Campus = user.nextToken();
String gender = user.nextToken();
role = user.nextToken();
if (LogID.equals(Id)) {
Toast.makeText(LoginActivity.this, "id is good", Toast.LENGTH_LONG).show();
if (PASS.equals(pas)) {
Toast.makeText(LoginActivity.this, "pass good", Toast.LENGTH_LONG).show();
found = true;
break;
}
}
if (found) {
Toast.makeText(LoginActivity.this, "break.", Toast.LENGTH_LONG).show();
break;
}
}
if (found) {
Toast.makeText(LoginActivity.this, "found", Toast.LENGTH_LONG).show();
if (role.equals("Security")) {
Intent accountsIntent = new Intent(LoginActivity.this, SecurityPage.class);
accountsIntent.putExtra("ID", LogID.getText().toString().trim());
} else {
Intent accountsIntent = new Intent(LoginActivity.this, StudentPage.class);
accountsIntent.putExtra("ID", LogID.getText().toString().trim());
}
} else
reader.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
this is the registration code, it has the same problem where anything after the BufferedReader is not executing.
package com.example.admin.projectfinal;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import com.example.admin.projectfinal.val.inputValidation;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener{
private TextInputLayout textInputLayoutName;
private TextInputLayout textInputLayoutId;
private TextInputLayout textInputLayoutPassword;
private TextInputLayout textInputLayoutDate;
TextInputEditText Name;
TextInputEditText id;
TextInputEditText Password;
TextInputEditText DOB;
Spinner campus;
Spinner Role;
Spinner Gender;
Button btn;
Button Cancel;
private inputValidation InputValidation;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Name = findViewById(R.id.name);
id = findViewById(R.id.ID);
Password = findViewById(R.id.password);
DOB = findViewById(R.id.dob);
btn = findViewById(R.id.next);
Cancel = findViewById(R.id.cancel);
campus = findViewById(R.id.campus);
Gender = findViewById(R.id.gender);
Role = findViewById(R.id.role);
textInputLayoutName = findViewById(R.id.NameLayout);
textInputLayoutId = findViewById(R.id.IdLayout);
textInputLayoutPassword = findViewById(R.id.PasswordLayout);
textInputLayoutDate = findViewById(R.id.DOBLayout);
//list for campus
String[] CampusList = new String[]{"MainCampus", "SasAlNakhlCampus", "MasdarCampus"};
ArrayAdapter<String> adapter1 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, CampusList);
campus.setAdapter(adapter1);
//list for gender
String[] gen = new String[]{"Male", "Female"};
ArrayAdapter<String> genAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, gen);
Gender.setAdapter(genAdapter);
//list for role
String[] rolee = new String[]{"Student", "Security"};
ArrayAdapter<String> roleAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, rolee);
Role.setAdapter(roleAdapter);
// Buttons validation
btn.setOnClickListener(this);
Cancel.setOnClickListener(this);
InputValidation = new inputValidation(RegisterActivity.this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.next:
try {
validate();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
break;
case R.id.cancel:
// Navigate to RegisterActivity
Intent intentRegister = new Intent(this, LoginActivity.class);
startActivity(intentRegister);
break;
}
}
private void validate() throws IOException {
boolean filled = true;
if (!InputValidation.isInputEditTextFilled(Name, textInputLayoutName, "Fill Name")) {
filled = false;
return;
}
if (!InputValidation.isInputEditTextFilled(id, textInputLayoutId, "Fill ID")) {
filled = false;
return;
}
if (!InputValidation.isInputEditTextFilled(DOB, textInputLayoutDate, "Fill Date")) {
filled = false;
return;
}
if (!InputValidation.isInputEditTextFilled(Password, textInputLayoutPassword, "Invalid Password")) {
filled = false;
return;
}
if (filled){
//if (!UserInfo.exists()) UserInfo.createNewFile();
String line;
boolean found = false;
BufferedReader reader= new BufferedReader(new FileReader("User.txt"));
Toast.makeText(getBaseContext(), "ready", Toast.LENGTH_LONG).show();
while ((line = reader.readLine()) != null) {
Toast.makeText(getBaseContext(), "while", Toast.LENGTH_LONG).show();
String[] user = line.split(" ");
String name = user[0];
String Id = user[1];
String dob = user[2];
String password = user[3];
String Campus = user[4];
String gender = user[5];
String role = user[6];
if (id.equals(Id)) {
found = true;
Toast.makeText(getBaseContext(), "User Exist", Toast.LENGTH_LONG).show();
break;
}
if (!found) {
// Adds a line to the file
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("User.txt")));
writer.append(Name + " " + id + " " + DOB + " " + Password + " "
+ campus.getSelectedItem() + " " + Gender.getSelectedItem() + " " + Role.getSelectedItem() + "/n" );
}
}
reader.close();
}
}
}
Input validation class I used in the code:
package com.example.admin.projectfinal.val;
import android.app.Activity;
import android.content.Context;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
public class inputValidation {
private static Context context;
/**
* constructor
*
* #param context
*/
public inputValidation(Context context) {
this.context = context;
}
/**
* method to check InputEditText filled .
*
* #param textInputEditText
* #param textInputLayout
* #param message
* #return
*/
public static boolean isInputEditTextFilled(TextInputEditText textInputEditText, TextInputLayout textInputLayout, String message) {
String value = textInputEditText.getText().toString().trim();
if (value.isEmpty()) {
textInputLayout.setError(message);
hideKeyboardFrom(textInputEditText);
return false;
} else {
textInputLayout.setErrorEnabled(false);
}
return true;
}
/**
* method to Hide keyboard
*
* #param view
*/
private static void hideKeyboardFrom(View view) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
}

Trigger an event when i return to an Event

Im trying to trigger an event when i return to an activity hitting the back button.
what i want to do is when i go back with the backbutton reload some items. Is there any way to do this?
here is my Main Activity where i want to do the "reload" of data, Some thing like "onResume" or "onReEnter"
package com.example.juanfri.seguridadmainactivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.androidquery.AQuery;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class ActivityTemporadaJson extends AppCompatActivity {
private String Nombre;
private int IdTmdb;
private String Tipo;
private int NumeroTemp;
private DBHelper mydb;
private ProgressDialog pDialog;
public final String API = "5e2780b2117b40f9e4dfb96572a7bc4d";
public final String URLFOTO ="https://image.tmdb.org/t/p/original";
private Temporada temp;
private TextView nombrePelicula;
private ImageView fotoPortada;
private TextView sinopsis;
private TextView NumEpsVal;
private TextView fechaLanzVal;
private ArrayList<Episodio> episodios;
private RecyclerView recyclerView;
private LinearLayoutManager mLinearLayoutManager;
private RecyclerAdapterEpisodio mAdapterEp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_temporada_json);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent recep = this.getIntent();
episodios = new ArrayList<>();
Nombre = recep.getStringExtra("Nombre");
Tipo = recep.getStringExtra("Tipo");
IdTmdb = Integer.parseInt(recep.getStringExtra("idSerie"));
NumeroTemp = Integer.parseInt(recep.getStringExtra("NumTemp"));
this.setTitle(Nombre);
nombrePelicula = (TextView) this.findViewById(R.id.NombrePelicula);
fotoPortada = (ImageView) this.findViewById(R.id.FotoPortada);
sinopsis = (TextView) this.findViewById(R.id.Sinopsis);
NumEpsVal = (TextView) this.findViewById(R.id.NumEpsVal);
fechaLanzVal = (TextView) this.findViewById(R.id.FechaLanzVal);
recyclerView = (RecyclerView) this.findViewById(R.id.recyclerviewEpisodios);
mydb = new DBHelper(this);
if (Tipo.equalsIgnoreCase("SQL")) {
Cursor res = mydb.getResultQuery("SELECT count(e.Visto) as numVisto FROM Episodio e, Temporada t WHERE t.IdTMDB = " + IdTmdb + " and e.IdTemporada = t.IdTemporada and e.NumeroTemporada = " + NumeroTemp + " and e.visto = 1");
res.moveToFirst();
int NumVisto = res.getInt(0);
mydb.UpdateEpsVistos(NumVisto, IdTmdb, NumeroTemp);
TextView NumEpsVis = (TextView) this.findViewById(R.id.EpsVis);
TextView NumEpsVisVal = (TextView) this.findViewById(R.id.EpsVisVal);
NumEpsVis.setVisibility(View.VISIBLE);
NumEpsVisVal.setVisibility(View.VISIBLE);
AQuery androidAQuery = new AQuery(this);
res = mydb.getResultQuery("SELECT Nombre, Sinopsis, FechaInicio, Poster, NumeroEpisodios,EpisodiosVistos FROM Temporada WHERE IdTMDB = " + IdTmdb + " and NumeroTemporada = " + NumeroTemp);
res.moveToFirst();
nombrePelicula.setText(res.getString(0));
sinopsis.setText(res.getString(1));
fechaLanzVal.setText(res.getString(2));
androidAQuery.id(fotoPortada).image(res.getString(3), true, true, 150, 0);
NumEpsVal.setText(Integer.toString(res.getInt(4)));
NumEpsVisVal.setText(Integer.toString(res.getInt(5)));
Cursor resEps = mydb.getResultQuery("SELECT e.Nombre, e.NumeroEpisodio, e.NumeroTemporada, e.FechaEmision, e.Sinopsis, e.Poster, e.Visto, e.IdEpisodio FROM Episodio e, Temporada t WHERE t.IdTMDB = " + IdTmdb + " and e.IdTemporada = t.IdTemporada and e.NumeroTemporada = " + NumeroTemp);
resEps.moveToFirst();
while (resEps.isAfterLast() == false) {
boolean visto = false;
if (resEps.getInt(6) == 1) {
visto = true;
}
Episodio nuevo = new Episodio(resEps.getInt(7), 0, resEps.getString(0), resEps.getInt(1), resEps.getInt(2), resEps.getString(3), resEps.getString(4), resEps.getString(5), visto);
episodios.add(nuevo);
resEps.moveToNext();
}
mLinearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(mLinearLayoutManager);
mAdapterEp = new RecyclerAdapterEpisodio(episodios, IdTmdb, Tipo);
recyclerView.setAdapter(mAdapterEp);
} else {
new GetTemp(this).execute();
}
//mydb = new DBHelper(this);
}
private class GetTemp extends AsyncTask<Void, Void, Void> {
Context c;
public GetTemp(Context c)
{
this.c = c;
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
//url = "https://api.themoviedb.org/3/tv/airing_today?api_key="+API+"&language=en-US&page="+pagina;
//https://api.themoviedb.org/3/tv/57243/season/1?api_key=5e2780b2117b40f9e4dfb96572a7bc4d&language=en-US
String url = "https://api.themoviedb.org/3/tv/"+IdTmdb+"/season/"+NumeroTemp+"?api_key="+API+"&language=es-ES";
String jsonStr = sh.makeServiceCall(url);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray episodes = jsonObj.getJSONArray("episodes");
String fecha = jsonObj.getString("air_date");
String nombreSerie = jsonObj.getString("name");
int numEps = episodes.length();
int numTemp = jsonObj.getInt("season_number");
String sinop = jsonObj.getString("overview");
String poster =URLFOTO + jsonObj.getString("poster_path");
// looping through All Contacts
for (int i = 0; i < episodes.length(); i++) {
JSONObject c = episodes.getJSONObject(i);
Episodio nuevo = new Episodio();
nuevo.setSinopsis(c.getString("overview"));
nuevo.setFechaEmision(c.getString("air_date"));
nuevo.setNombreEpisodio(c.getString("name"));
nuevo.setNumeroEpisodio(c.getInt("episode_number"));
nuevo.setNumeroTemporada(c.getInt("season_number"));
nuevo.setPoster(URLFOTO + c.getString("still_path"));
episodios.add(nuevo);
}
temp = new Temporada(0, IdTmdb, nombreSerie, sinop, fecha, poster, numTemp,false, 0, numEps, episodios);
} catch (final JSONException e) {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
} else {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
AQuery androidAQuery=new AQuery(c);
// Dismiss the progress dialog
if (pDialog.isShowing())
{
pDialog.dismiss();
}
androidAQuery.id(fotoPortada).image(temp.getPoster(), true, true, 150,0);
String Nombre = "Temporada " + temp.getNumeroTemporada();
nombrePelicula.setText(Nombre);
sinopsis.setText(temp.getSinopsis());
NumEpsVal.setText(Integer.toString(temp.getNumeroEpisodios()));
fechaLanzVal.setText(temp.getFechaInicio());
mLinearLayoutManager = new LinearLayoutManager(c, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(mLinearLayoutManager);
mAdapterEp = new RecyclerAdapterEpisodio(temp.getEpisodios(),IdTmdb,Tipo);
recyclerView.setAdapter(mAdapterEp);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(c);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
}
}
You can use onRestart , which will be triggered when existing activity will be bought back to front .
As quoted in docs
Called after onStop() when the current activity is being re-displayed
to the user (the user has navigated back to it). It will be followed
by onStart() and then onResume().
so Override onRestart
#Override
public void onRestart() {
// you come back to me
}

Problemto Create a Class SQL Query Studio Android

My Problem today is that been developing an APP having a Login, A Maintenance Products (For more say), all with the database engine SQL
and create the login all Ok, the procedimeinto a normal login with user and pass ago, also believes maintaining create products, which I take as parameters the name of the product and its respective description, I add, edit, and delete, just not makes the management of search data and show me when access to the corresponding layout, using the onCreate method of my MainMenu but hey that's not the case, the relevant case is that I want to know how to do that through a button, find me the names input on a EditText or are related to the name, and tried to do this using the following code:
package com.sqldata.gst.appsql;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* Created by Administrador on 05/10/2016.
*/
public class ConClientes extends MainActivity {
Conexion conexionSQL;
EditText txtCdCliente, txtNomCli;
Button btnBuscar, btnRetornar;
ProgressBar pgrCliente;
ListView lstClientes;
String idCliente;
//ResultSet rs;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.con_clientes);
conexionSQL = new Conexion();
txtCdCliente = (EditText) findViewById(R.id.txtCdCliente);
//txtNomCli = (EditText) findViewById(R.id.txtNomCli);
btnBuscar = (Button) findViewById(R.id.btnBuscar);
btnRetornar = (Button) findViewById(R.id.btnRetornar);
pgrCliente = (ProgressBar) findViewById(R.id.pgrCliente);
lstClientes = (ListView) findViewById(R.id.lstClientes);
pgrCliente.setVisibility(View.GONE);
idCliente = "";
// Evento Ejecutar Boton
btnBuscar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SelectClientes selectClientes = new SelectClientes();
selectClientes.execute(""); //Cannot resolve method 'execute(java.lang.String)
}
});
}
public class FillList extends AsyncTask<String, String, String>
{
String result = "";
List<Map<String, String>> CliList = new ArrayList<Map<String, String>>();
#Override
protected void onPreExecute(){
pgrCliente.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String r){
pgrCliente.setVisibility(View.GONE);
Toast.makeText(ConClientes.this, r, Toast.LENGTH_SHORT).show();
String[] from = {"A", "B", "C"};
int[] views = {R.id.lblClienteId, R.id.lblNomCli, R.id.lblCodCli};
final SimpleAdapter ADA = new SimpleAdapter(ConClientes.this, CliList, R.layout.lst_cliente,
from, views);
lstClientes.setAdapter(ADA);
lstClientes.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
HashMap<String, Object> obj = (HashMap<String, Object>) ADA.getItem(arg2);
idCliente = (String) obj.get("A");
//String ClienName = (String) obj.get("B");
String ClienCod = (String) obj.get("C");
//txtNomCli.setText(ClienName);
txtCdCliente.setText(ClienCod);
}
});
}
#Override
protected String doInBackground (String... params){
try{
Connection cnSQL = conexionSQL.CONN();
if (cnSQL == null){
result = "Error en la Conexión SQL Server";
}
else{
String query = "select * from clientes";
PreparedStatement psSQL = cnSQL.prepareStatement(query);
ResultSet rsSQL = psSQL.executeQuery();
ArrayList data1 = new ArrayList();
while (rsSQL.next()){
Map<String, String> dataRec = new HashMap<String, String>();
dataRec.put("A", rsSQL.getString("idcliente"));
dataRec.put("B", rsSQL.getString("nom_cli"));
dataRec.put("C", rsSQL.getString("cod_cli"));
CliList.add(dataRec);
}
result = "Success";
}
} catch (Exception ex){
result = "Error al Buscar Datos de la Tabla Clientes";
}
return result;
}
}
public class SelectClientes extends ArrayList<String>{
String result = "";
Boolean isSuccess = false;
String ClienCod = txtCdCliente.getText().toString();
String NomCli = txtNomCli.getText().toString();
#Override //Method does not override method from its superclass
protected void onPreExecute(){
pgrCliente.setVisibility(View.VISIBLE);
}
//#Override
protected void onPostExecute(String r){
pgrCliente.setVisibility(View.GONE);
Toast.makeText(ConClientes.this, r, Toast.LENGTH_SHORT).show();
if (isSuccess == true){
FillList fillList = new FillList();
fillList.execute("");
}
}
#Override //Method does not override method from its superclass
protected String doInBackground(String... params){
if (ClienCod.trim().equals(""))
result = "Favor de Introducir el Codigo del Cliente";
else {
try{
Connection con = conexionSQL.CONN();
if (con == null){
result = "No Hay Datos para Mostrar";
} else {
String query = "Select * from clientes where idcliente =" + idCliente;
PreparedStatement preparedStatement = con.prepareStatement(query);
preparedStatement.executeUpdate();
result = "Busqueda de Datos Correcta";
isSuccess = true;
}
} catch (Exception ex){
isSuccess = false;
result = "Verifique los Datos";
}
}
return result;
}
}
}
Well as observed that that's my code and attempted but has two factors which are commented code the first is:
selectClientes.execute(""); // Can not resolve method 'execute (java.lang.String)
and the second in the Override
#Override //Method does not override method from its superclass
that's my niggle I do not understand how I can do to make me query consisting of editext = that will be the name or names that seeketh, and the button to execute the action of select * from, you understand me
and I would like to step I make when entering the layout from the menu to load and show me the data, without pressing anything
such as doInBackground method that's what I want to do but I guess it's in the onCreate and you will understand me if you need more details, please say, what I want is to solve that little problem
Thanks to All!!
Of course app can't resolve method execute, because ArrayList doesn't have it.
SelectClientes extends ArrayList
SelectClientes should extend AsyncTask.

How to know that specific document is present in Cloudant Database using Android App

I have successfully created document in Cloudant database through my Android App. But I can not find a specific document present in Cloudant database. What I have tried is like below....
TabTwo_Fragment.java
package com.example.android02.insightapp11;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.cloudant.sync.datastore.BasicDocumentRevision;
import com.cloudant.sync.datastore.Datastore;
import com.cloudant.sync.datastore.DatastoreManager;
import com.cloudant.sync.datastore.DatastoreNotCreatedException;
import com.cloudant.sync.datastore.DocumentBodyFactory;
import com.cloudant.sync.datastore.DocumentException;
import com.cloudant.sync.datastore.DocumentNotFoundException;
import com.cloudant.sync.datastore.DocumentRevision;
import com.cloudant.sync.datastore.MutableDocumentRevision;
import com.cloudant.sync.replication.Replicator;
import com.cloudant.sync.replication.ReplicatorBuilder;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
/**
* A simple {#link Fragment} subclass.
*/
public class TabTwo_Fragment extends Fragment implements View.OnClickListener, SharedPreferences.OnSharedPreferenceChangeListener {
private static final String DATASTORE_MANGER_DIR = "data";
private static final String TASKS_DATASTORE_NAME = "tasks";
Datastore DataStore;
private Replicator PushReplicator, PullReplicator;
DocumentRevision revision;
static final String CLOUDANT_USER = "user_default";
static final String CLOUDANT_DB = "database_name";
static final String CLOUDANT_API_KEY = "api_key";
static final String CLOUDANT_API_SECRET = "api_key_pwd";
long TWITTER_ID = MainActivity.twitterID;
String TWITTER_NAME = MainActivity.userName;
Button btn_submit;
Spinner sp1, sp2, sp3, sp4, sp5, sp6, sp7, sp8;
TextView ans_total;
String user = "old";
HashMap<String, String> qa_hashmap;
public TabTwo_Fragment() {
// Required empty public constructor
}
public static TabTwo_Fragment newInstance() {
return new TabTwo_Fragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tabtwo_fragment, container, false);
try {
init(rootView);
} catch (DocumentNotFoundException e) {
} catch (DocumentException e) {
} catch (URISyntaxException e) {
}
return rootView;
}
void init(View rootView) throws DocumentException, URISyntaxException {
Log.e("init: ", "in init");
find_view_by_id(rootView);
registerClickEvents();
defaultConfig();
checkForRegisteredUser();
}
void find_view_by_id(View rootView) {
Log.e("find_view_by_id: ", "in find_view_by_id");
btn_submit = (Button) rootView.findViewById(R.id.btn_submit);
sp1 = (Spinner) rootView.findViewById(R.id.sp1);
sp2 = (Spinner) rootView.findViewById(R.id.sp2);
sp3 = (Spinner) rootView.findViewById(R.id.sp3);
sp4 = (Spinner) rootView.findViewById(R.id.sp4);
sp5 = (Spinner) rootView.findViewById(R.id.sp5);
sp6 = (Spinner) rootView.findViewById(R.id.sp6);
sp7 = (Spinner) rootView.findViewById(R.id.sp7);
sp8 = (Spinner) rootView.findViewById(R.id.sp8);
ans_total = (TextView) rootView.findViewById(R.id.ans_total);
}
void registerClickEvents() {
Log.e("registerClickEvents: ", "in registerClickEvents");
btn_submit.setOnClickListener(this);
}
void defaultConfig() {
Log.e("defaultConfig: ", "in defaultConfig");
PreferenceManager.setDefaultValues(getContext(), R.xml.preferences, false);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
sharedPref.registerOnSharedPreferenceChangeListener(this);
File path = getContext().getDir(DATASTORE_MANGER_DIR, Context.MODE_PRIVATE);
DatastoreManager manager = new DatastoreManager(path.getAbsolutePath());
try {
DataStore = manager.openDatastore(TASKS_DATASTORE_NAME);
setUriPlusReplicators();
} catch (DatastoreNotCreatedException e) {
Toast.makeText(getContext(), "Unable to open Datastore!", Toast.LENGTH_SHORT).show();
} catch (URISyntaxException e) {
Toast.makeText(getContext(), "URI Exception!!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
try {
setUriPlusReplicators();
} catch (URISyntaxException e) {
}
}
void setUriPlusReplicators() throws URISyntaxException {
Log.e("setUriPlusReplicators: ", "in setUriPlusReplicators");
URI uri = this.createServerUri();
Log.e("URI: ", "" + uri);
PushReplicator = ReplicatorBuilder.push().from(DataStore).to(uri).build();
PushReplicator.getEventBus().register(this);
PullReplicator = ReplicatorBuilder.pull().to(DataStore).from(uri).build();
PullReplicator.getEventBus().register(this);
}
private URI createServerUri() throws URISyntaxException {
Log.e("createServerUri: ", "in createServerUri");
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
String username = sharedPref.getString(CLOUDANT_USER, "");
String dbName = sharedPref.getString(CLOUDANT_DB, "");
String apiKey = sharedPref.getString(CLOUDANT_API_KEY, "");
String apiSecret = sharedPref.getString(CLOUDANT_API_SECRET, "");
String host = username + ".cloudant.com";
return new URI("https", apiKey + ":" + apiSecret, host, 443, "/" + dbName, null, null);
}
private URI createServerUri2(long twitterId) throws URISyntaxException {
Log.e("createServerUri2: ", "in createServerUri2");
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
String username = sharedPref.getString(CLOUDANT_USER, "");
String dbName = sharedPref.getString(CLOUDANT_DB, "");
String apiKey = sharedPref.getString(CLOUDANT_API_KEY, "");
String apiSecret = sharedPref.getString(CLOUDANT_API_SECRET, "");
String host = username + ".cloudant.com";
return new URI("https", apiKey + ":" + apiSecret, host, 443, "/" + dbName + "/_all_docs?", null, null);
}
void checkForRegisteredUser() throws DocumentNotFoundException, DocumentException, URISyntaxException {
BasicDocumentRevision retrieved = DataStore.getDocument(TWITTER_ID + "");
if (user.equals("new")) {
setQuizData(retrieved.getBody().toString());
} else {
newUser();
}
}
void setQuizData(String DataRetrieved) {
Log.e("setQuizData: ", "In setQuizData");
user = "old";
Log.e("DataRetrieved: ", "In " + DataRetrieved);
String[] ANSWERS = getResources().getStringArray(R.array.ans);
try {
JSONObject jsonObject = new JSONObject(DataRetrieved);
JSONObject jsonObject1 = jsonObject.getJSONObject("questions");
String qs1 = jsonObject1.getString("q1");
String qs2 = jsonObject1.getString("q2");
String qs3 = jsonObject1.getString("q3");
String qs4 = jsonObject1.getString("q4");
String qs5 = jsonObject1.getString("q5");
String qs6 = jsonObject1.getString("q6");
String qs7 = jsonObject1.getString("q7");
String qs8 = jsonObject1.getString("q8");
sp1.setSelection(Arrays.asList(ANSWERS).indexOf(qs1));
sp2.setSelection(Arrays.asList(ANSWERS).indexOf(qs2));
sp3.setSelection(Arrays.asList(ANSWERS).indexOf(qs3));
sp4.setSelection(Arrays.asList(ANSWERS).indexOf(qs4));
sp5.setSelection(Arrays.asList(ANSWERS).indexOf(qs5));
sp6.setSelection(Arrays.asList(ANSWERS).indexOf(qs6));
sp7.setSelection(Arrays.asList(ANSWERS).indexOf(qs7));
sp8.setSelection(Arrays.asList(ANSWERS).indexOf(qs8));
} catch (JSONException e) {
}
}
void newUser() {
Log.e("newUser: ", "In newUser");
user = "new";
}
void createDocument() throws DocumentException {
Log.e("createDocument: ", "In createDocument");
MutableDocumentRevision rev = new MutableDocumentRevision();
rev.docId = TWITTER_ID + "";
gatherQAData();
/*HashMap<String, Object> map_main = new HashMap<String, Object>();*/
HashMap<String, Object> map = new HashMap<String, Object>();
ArrayList<HashMap<String, Object>> arrayTeachers = new ArrayList<>();
map.put("twitter_id", TWITTER_ID + "");
map.put("twitter_name", TWITTER_NAME);
map.put("questions", qa_hashmap);
/*arrayTeachers.add(map);*/
/*map_main.put("user", arrayTeachers);*/
rev.body = DocumentBodyFactory.create(map);
revision = DataStore.createDocumentFromRevision(rev);
PushReplicator.start();
}
void updateDocument() {
Log.e("updateDocument: ", "In updateDocument");
}
void gatherQAData() {
Log.e("gatherQAData: ", "In gatherQAData");
qa_hashmap = new HashMap<String, String>();
String a1, a2, a3, a4, a5, a6, a7, a8;
a1 = sp1.getSelectedItem().toString();
a2 = sp2.getSelectedItem().toString();
a3 = sp3.getSelectedItem().toString();
a4 = sp4.getSelectedItem().toString();
a5 = sp5.getSelectedItem().toString();
a6 = sp6.getSelectedItem().toString();
a7 = sp7.getSelectedItem().toString();
a8 = sp8.getSelectedItem().toString();
qa_hashmap.put("q1", a1);
qa_hashmap.put("q2", a2);
qa_hashmap.put("q3", a3);
qa_hashmap.put("q4", a4);
qa_hashmap.put("q5", a5);
qa_hashmap.put("q6", a6);
qa_hashmap.put("q7", a7);
qa_hashmap.put("q8", a8);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_submit:
if (user.equals("new")) {
try {
createDocument();
} catch (DocumentException e) {
}
} else {
updateDocument();
}
break;
default:
}
}
}
I can get the document which is stored in DataStore. But I am unable to get document stored in Cloudant database.
FYI: I am finding document in checkForRegisteredUser method.
Yes, I have done it. Below is my code for checkForRegisteredUser method of TabTwo_Fragment.java
void checkForRegisteredUser() {
String url = "https://your_cloudant_user_name.cloudant.com/" + DB_NAME + "/" + DOC_ID;
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, url, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if (response.toString().length() > 0) {
setQuizData(response.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
newUser();
}
});
requestQueue.add(jor);
Here is s Official Documentation LINK.
Here DOC_ID is the id of document that you want to check. Hope this will help to somebody.
What happens in Cloudant is that there are already two fields by default given by cloudant to each document namely _id and _rev where _id acts as primarykey for indexing. So there will be a default index created by cloudant on the _id field. If you already have these fields in your document than cloudant won't insert extra _id and _rev.
Now you can have this _id field in your document and set it according to yourself or let cloudant set it. But when you are not setting it than you won't be able to query Cloudant on the primary index because you don't know the _id of the document.
So to search or find on basis of some other field like the twitter_id as you have stored you have to create one more index than you'll be able to search/find according to that.
we can create index in java using the function provided by cloudant api
public void createIndex(java.lang.String indexName,
java.lang.String designDocName,
java.lang.String indexType,
IndexField[] fields)
or If you are assigning _id in your function than you can simply call a function
db.contains(doc_id);
which is a lot easier as you don't need to create any index and using default index.
EDIT-1
So the db here is the database instance you have acquired.
Database db=client.database(db_name,create_flag);
where create_flag is a boolean to if the database should be created if not existed so true means yes create false means no don't create if not there.
and client is CloudantClient object.
But alternatively you can call createDB also if you know the db is not there. You can do it as follow
Database db=client.createDB("DBNAME");
How to get a CloudantClient is dependent on the version of cloudant api you are using. for ex 1.0.1 is different from the latest.
in version 1.0.1 you do it as follow
CloudantClient client=new CloudantClient(URL_OF_YOUR_CLOUDANT,USERNAME,PASSWORD);
But in latest release they use
CloudantClient client=ClientBuilder.url(new URL("your url")).username("your username string").password("your password").build();
SO I don't know why you were not able to find createIndex. I suppose you are unable to find Cloudant-api javadocs .Just google for Cloudant javadocs or check this github
GitHub link

Categories

Resources