Access database from android phone through android app - android

i am currently developping an application for my third year project, it's an android app (i used android studio) that will access a database that i created on my wamp server, the connection works perfectly from the application when i debug it on my android phone( i used in my code the "HttpURLConnection" with the url being my pc ip adress that i got from (cmd/ipconfig) ) .
The problem is that once i disconnect my phone from my pc and try to run the application from the phone, the connection with the database won't work, and also if i connect my pc to another modem, my pc ip changes, which is pretty much normal, but i don't think supposed to change the ip everytime the modem i connect to change ( although i'm not really sure, server connexions are clearly not something i'm an expert at ) , so i tried to use the ip of my pc on the internet that i got from "ipaddress.com" but it won't work, not even if i debug the application directly from android studio,
i don't have much time left to present the application , so i need a quick answer, thank you in advance
P.S : i guess i gotta mention that i need to acces the database to read AND write on it from the phone since it's an app that permits login/registration and will get the data that the user will enter and store it in the database .

I don't know wheter understanded, when you disconnect your phone from your pc, the app dead? or simplely it don't connect with db. Regard router, you need an account in "no-ip" and configure forguard's router on port 80 to redirect your computer's static IP. i need more details and information to help you. Regards

Try to connect the Phone and Mobile in same network.
your connection Url would be Like this 192.10.20.2 which is your ip or computer. as your get it form cmd using ipconfig command.
but whenever your networks changes your have to decompile to change the ip. or provide ip via textview.
take a Editview to take ip. and the concat it to your url. this will work. as it worked for me.

i'm working on an external server
The php code (for the connection to the db)
<?php
$db_name="pfe";
$mysql_username="root";
$mysql_password="";
$server_name="localhost";
$conn = mysqli_connect($server_name,$mysql_username,$mysql_password,$db_name);
?>
then i got another php file which handles the login part
<?php
require "connexion.php";
$user_email =$_POST["user-email"];
$user_pass =$_POST["password"];
$mysql_qry = "select id from donateur where email like '$user_email' and
password like '$user_pass'";
$result = mysqli_query($conn , $mysql_qry);
if(($row=mysqli_fetch_assoc($result))!=null){
$a = array('myarray' => array("donateur", $row["id"]));
echo json_encode($a);}
else {
$mysql_qry2 = "select id, username from association where email like
'$user_email' and password like '$user_pass'";
$result2 = mysqli_query($conn , $mysql_qry2);
if(($row=mysqli_fetch_assoc($result2))!=null) { $a = array('myarray' =>
array("association", $row["id"]));
echo json_encode($a);
}
else { echo "rien";}}
$conn->close();
the java code :
package applis.pfe;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static android.Manifest.permission.READ_CONTACTS;
public class LoginActivity extends AppCompatActivity implements
LoaderCallbacks<Cursor> {
/**
* Id to identity READ_CONTACTS permission request.
*/
private static final int REQUEST_READ_CONTACTS = 0;
DonateurDAO donateurdao= new DonateurDAO(this);
AssociationDAO associationdao=new AssociationDAO(this);
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
String ip="http://105.101.179.155/";
private UserLoginTask mAuthTask = null;
// UI references.
private AutoCompleteTextView mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
public static String qui;
public static int id;
public static String username;
SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
///////////////////// POUR AFFICHER LE MESSAGE DIINSCRIPTION REUSSIE /////////////////////////////////////
if(getIntent().getStringExtra("inscription")!=null &&
getIntent().getStringExtra("inscription").equals("oui"))
{ AlertDialog a= new AlertDialog.Builder(LoginActivity.this).create();
a.setTitle("Inscription réussie !");
a.setMessage("Votre inscription a été validé, veuillez vous connecter
pour pouvoir continuer");
a.show();}
session = new SessionManager(this);
// Set up the login form.
mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
// populateAutoComplete();
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new
TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int id, KeyEvent
keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mEmailSignInButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
ImageButton btn;
btn =(ImageButton)findViewById(R.id.InscriptionDonateurButton);
btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {Intent in= new
Intent(LoginActivity.this,InscriptionDonateurActivity.class);
startActivity(in);
}
});
ImageButton btn1;
btn1 =(ImageButton)findViewById(R.id.InscriptionAssociationButton);
btn1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {Intent in= new
Intent(LoginActivity.this,InscriptionAssociationActivity.class);
startActivity(in);
}
});
}
private void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mEmailView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
String email = mEmailView.getText().toString();
String password = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(email)) {
mEmailView.setError(getString(R.string.error_field_required));
focusView = mEmailView;
cancel = true;
} else if (!isEmailValid(email)) {
mEmailView.setError(getString(R.string.error_invalid_email));
focusView = mEmailView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
showProgress(true);
mAuthTask = new UserLoginTask(email, password);
mAuthTask.execute((Void) null);
}
}
private boolean isEmailValid(String email) {
//TODO: Replace this with your own logic
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
private boolean isPasswordValid(String password) {
//TODO: Replace this with your own logic
return password.length() > 4;
}
/**
* Shows the progress UI and hides the login form.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact.
Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
// Select only email addresses.
ContactsContract.Contacts.Data.MIMETYPE +
" = ?", new String[]{ContactsContract.CommonDataKinds.Email
.CONTENT_ITEM_TYPE},
// Show primary email addresses first. Note that there won't be
// a primary email address if the user hasn't specified one.
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}
#Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
List<String> emails = new ArrayList<>();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
emails.add(cursor.getString(ProfileQuery.ADDRESS));
cursor.moveToNext();
}
addEmailsToAutoComplete(emails);
}
#Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
}
private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
//Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
ArrayAdapter<String> adapter =
new ArrayAdapter<>(LoginActivity.this,
android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
mEmailView.setAdapter(adapter);
}
private interface ProfileQuery {
String[] PROJECTION = {
ContactsContract.CommonDataKinds.Email.ADDRESS,
ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
};
int ADDRESS = 0;
int IS_PRIMARY = 1;
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<Void, Void, String> {
private final String mEmail;
private final String mPassword;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}
#Override
protected String doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
String login_url= ip.concat("login.php");
try {
URL url= new URL(login_url);
HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
OutputStream outputStream= httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter= new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String Post_data= URLEncoder.encode("user-email","UTF-8")+"="+URLEncoder.encode(mEmail,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(mPassword,"UTF-8");
bufferedWriter.write(Post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream=httpURLConnection.getInputStream();
qui=null;
id=0;
BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String resultat="";
String ligne="";
while((ligne=bufferedReader.readLine())!=null)
resultat += ligne;
if (resultat.equals("rien")) return resultat; else {
JSONObject jsonObject = new JSONObject(resultat);
JSONArray json_data = jsonObject.getJSONArray("myarray");
qui=json_data.getString(0);
id=json_data.getInt(1);
username= json_data.getString(2);}
/* for(int i=0;i<json_data.length();i++)
{
k++;
qui= json_data.getString(1);
id= json_data.getInt(2);
//r.add(json_data.getString("categorie"));
}*/
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return resultat;
} catch (MalformedURLException e) {
e.printStackTrace();return e.toString();
} catch (IOException e) {
e.printStackTrace();return e.toString();
} catch (JSONException e) {
e.printStackTrace(); return e.toString();
}
}
/* for (String credential : DUMMY_CREDENTIALS) {
String[] pieces = credential.split(":");
if (pieces[0].equals(mEmail)) {
// Account exists, return true if the password matches.
return pieces[1].equals(mPassword);
}
}*/
// TODO: register the new account here.
#Override
protected void onPostExecute(String resultat) {
mAuthTask = null;
showProgress(false);
/////////////////////////////////////////////////////////////////////////////////
Intent i;
AlertDialog a;
if (resultat.equals("rien")){i= new Intent(LoginActivity.this,LoginActivity.class);
a= new AlertDialog.Builder(LoginActivity.this).create();
a.setTitle("Erreur");
a.setMessage(" Email et/ou mot de passe erroné(s)");
a.show();} else {
try {
session.createLoginSession(mEmail,username,qui,id);
session.checkLogin();
if (qui.equals("donateur")) {
i = new Intent(LoginActivity.this, Suite_Inscription_Donateur.class);
i.putExtra("id", id);
startActivity(i);
} else if (qui.equals("association")) {
session.createLoginSession(mEmail,username,qui,id);
i = new Intent(LoginActivity.this, Suite_Inscription_Association.class);
i.putExtra("id", id);
startActivity(i);
}
} catch (Exception e) {
e.printStackTrace();
a= new AlertDialog.Builder(LoginActivity.this).create();
a.setTitle("Erreur");
a.setMessage("Erreur :".concat(e.toString()));
a.show();
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
}

Related

error: package net.sourceforge.jtds.jdbc does not exist

i'm trying to connect to SQL Server Database from android studio
i'm using jtds and already import "jtds-1.3.1.jar" module to android studio
in the import part below line i got error
import net.sourceforge.jtds.jdbc.*;
and the error is:
"error: package net.sourceforge.jtds.jdbc does not exist"
. i don't know what i miss.
package com.example.mycar4;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.support.v7.app.ActionBarActivity;
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;
import net.sourceforge.jtds.jdbc.*;
public class database 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;
String usernam,passwordd;
//End Declaring connection variables
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_database);
// Getting values from button, texts and progress bar
login = (Button) findViewById(R.id.btn_Login);
username = (EditText) findViewById(R.id.et_username);
password = (EditText) findViewById(R.id.et_password);
progressBar = (ProgressBar) findViewById(R.id.pbbar);
progressBar.setVisibility(View.GONE);
// End Getting values from button, texts and progress bar
// Declaring Server ip, username, database name and password
ip = "***";
db = "***";
un = "***";
pass = "***";
// 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)
{
usernam = username.getText().toString();
passwordd = password.getText().toString();
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(database.this, r, Toast.LENGTH_SHORT).show();
if(isSuccess)
{
Toast.makeText(database.this , "Login Successfull" , Toast.LENGTH_LONG).show();
//finish();
}
}
#Override
protected String doInBackground(String... params)
{
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
{
String query = "select * from login where username= '" + usernam.toString() + "' and password = '"+ 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").newInstance();
ConnectionURL = "jdbc:jtds:sqlserver://sql5009.mywindowshosting.com;database=DB_A2C00B_login;user=DB_A2C00B_login_admin;password=login#123";
// ConnectionURL =
"jdbc:jtds:sqlserver://192.168.1.9;database=msss;instance=SQLEXPRESS;Network
Protocol=NamedPipes" ;
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;
}
}
To connect an Android App with a SQL server, you'll need to set up a web (Http) server in between the two. You can build this web server in any language you're familiar with be it java (J2EE) or php etc.
This web server will be hosted with your SQL server and will take Http requests from the Android app, process it, forward the request as queries to your SQL server and then return it back to your app as REST/JSON (the current format of sending data over the web) or SOAP/XML (the old way of sending data over the web).
App >> Web Server >> Database Server
The web server should be RESTful and the app can interact with it via Http requests via the library Retrofit2.
Here's some resources to get you started;
Retrofit by Square.
Retrofit Github repository.
Simple CRUD example with Java RESTful Web Service, a brief tutorial.
RESTful Web Services: A Tutorial Android + Java Web Services
if you are using android studio or eclipse you should put the jtds jar file in the correct location
it is in the libs (library) folder inside app n your project. Once you put it in the libs > right click then add library.
another note you should use 1.2.7 or lower which is much supported

Android Popup help - not appearing

I am trying to load a popup window that contains an edittext and a datepicker.
I have included my code below.
Basically the initial window is closed as expected, but my pop up doesn't appear?
I have checked the xml call and the id is correct, no errors and for some reason my logcat in eclipse has stopped working but thats a different issue!
Hopefully someone can tell me what I have missed and / or doing wrong? I am new to android programming so please ignore my ignorance if it is something simple!
package com.zelphe.zelpheapp;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import com.zelphe.zelpheapp.library.DatabaseHandler;
import com.zelphe.zelpheapp.library.UserFunctions;
public class LoginActivity extends Activity
{
Button btnLogin;
Button Btnregister;
Button passreset;
EditText inputEmail, inputName, inputPassword;
DatePicker inputDOB;
private TextView loginErrorMsg;
/**
* Called when the activity is first created.
*/
private static String KEY_SUCCESS = "success";
private static String KEY_REGISTER = "doRegister";
private static String KEY_UID = "uid";
private static String KEY_USERNAME = "uname";
private static String KEY_FIRSTNAME = "fname";
private static String KEY_LASTNAME = "lname";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
Button btnReg;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_test);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.loginbtn);
//loginErrorMsg = (TextView) findViewById(R.id.loginErrorMsg);
/**
* Login button click event
* A Toast is set to alert when the Email and Password field is empty
**/
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if ( ( !inputEmail.getText().toString().equals("")) && ( !inputPassword.getText().toString().equals("")) )
{
NetAsync(view);
}
else if ( ( !inputEmail.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(),
"Password field empty", Toast.LENGTH_SHORT).show();
}
else if ( ( !inputPassword.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(),
"Email field empty", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),
"Email and Password field are empty", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Async Task to check whether internet connection is working.
**/
private class NetCheck extends AsyncTask<String,String,Boolean>
{
private ProgressDialog nDialog;
#Override
protected void onPreExecute(){
super.onPreExecute();
nDialog = new ProgressDialog(LoginActivity.this);
nDialog.setTitle("Checking Network");
nDialog.setMessage("Loading..");
nDialog.setIndeterminate(false);
nDialog.setCancelable(false);
nDialog.show();
}
/**
* Gets current device state and checks for working internet connection by trying Google.
**/
#Override
protected Boolean doInBackground(String... args){
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
#Override
protected void onPostExecute(Boolean th){
if(th == true){
nDialog.dismiss();
new ProcessLogin().execute();
}
else{
nDialog.dismiss();
loginErrorMsg.setText("Error in Network Connection");
}
}
}
/**
* Async Task to get and send data to My Sql database through JSON respone.
**/
private class ProcessLogin extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
String email,password;
#Override
protected void onPreExecute() {
super.onPreExecute();
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
email = inputEmail.getText().toString();
password = inputPassword.getText().toString();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Logging in ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(email, password);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
pDialog.setMessage("Loading User Space");
pDialog.setTitle("Getting Data");
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
/**
* Clear all previous data in SQlite database.
**/
UserFunctions logout = new UserFunctions();
logout.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_FIRSTNAME),json_user.getString(KEY_LASTNAME),json_user.getString(KEY_EMAIL),json_user.getString(KEY_USERNAME),json_user.getString(KEY_UID),json_user.getString(KEY_CREATED_AT));
/**
*If JSON array details are stored in SQlite it launches the User Panel.
**/
Intent upanel = new Intent(getApplicationContext(), MainActivity.class);
upanel.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pDialog.dismiss();
startActivity(upanel);
/**
* Close Login Screen
**/
finish();
}else if(Integer.parseInt(res) == 2)
{
pDialog.dismiss();
Toast.makeText(getApplicationContext(),
"Incorrect Password!", Toast.LENGTH_SHORT).show();
}
else
{
pDialog.dismiss();
initiatePopupWindow();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private PopupWindow pwindo;
private void initiatePopupWindow()
{
try
{
// We need to get the instance of the LayoutInflater
LayoutInflater inflater = (LayoutInflater) LoginActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.activity_register,(ViewGroup)
findViewById(R.id.popup_element));
pwindo = new PopupWindow(layout, 350, 350, true);
pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
btnReg = (Button) layout.findViewById(R.id.btnReg);
btnReg.setOnClickListener((android.view.View.OnClickListener) reguser);
}
catch (Exception e)
{
e.printStackTrace();
}
}
private OnClickListener reguser = new OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
inputName = (EditText) findViewById(R.id.name);
inputDOB = (DatePicker) findViewById(R.id.dob);
if ( ( !inputName.getText().toString().equals("")) &&
( getAge(inputDOB.getDayOfMonth(), inputDOB.getMonth(), inputDOB.getYear()) > 15) )
{
//register user
}
else if ( ( inputName.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(),
"Please enter your name", Toast.LENGTH_SHORT).show();
}
else if (( getAge(inputDOB.getDayOfMonth(), inputDOB.getMonth(), inputDOB.getYear()) < 16) )
{
Toast.makeText(getApplicationContext(),
"You must be at least 16 to use this app", Toast.LENGTH_SHORT).show();
}
}
};
}
public int getAge (int _year, int _month, int _day) {
GregorianCalendar cal = new GregorianCalendar();
int y, m, d, a;
y = cal.get(Calendar.YEAR);
m = cal.get(Calendar.MONTH);
d = cal.get(Calendar.DAY_OF_MONTH);
cal.set(_year, _month, _day);
a = y - cal.get(Calendar.YEAR);
if ((m < cal.get(Calendar.MONTH))
|| ((m == cal.get(Calendar.MONTH)) && (d < cal
.get(Calendar.DAY_OF_MONTH)))) {
--a;
}
if(a < 0)
throw new IllegalArgumentException("Age < 0");
return a;
}
public void NetAsync(View view){
new NetCheck().execute();
}
}
Embarassingly enough, there is no issue with the popup, I had an error further up in my code, doh!

Connecting to FTP server using AsyncTask

I am quite new to android developing
I have written the following code to connect my android to a ftp server
package com.example.test1;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import org.apache.commons.net.ftp.*;
public class MainActivity extends Activity {
public FTPClient mFTPClient = null;
Button but;
public boolean ftpConnect(String host, String username, String password, int port) {
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect(host, port);
// Now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// Login using username & password
boolean status = mFTPClient.login(username, password);
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
mFTPClient.enterLocalPassiveMode();
return status;
}
} catch(Exception e) {
CharSequence c = ""+e;
int d = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(),c,d);
toast.show();
}
return false;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
but=(Button)findViewById(R.id.button1);
but.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ftpConnect("127.0.0.1","userName","Password",21);
}
});
}
}
But this gives a networkOnMainThread Exception so after searching i found out i have to use AsyncTask but i have no idea how to implement it!
public void onClick(View v) {
new AsyncTask() {
publc Object doInBackground(Object...) {
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect(host, port);
// Now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// Login using username & password
boolean status = mFTPClient.login(username, password);
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
mFTPClient.enterLocalPassiveMode();
return status;
}
} catch(Exception e) {
return e;
}
}
}
public void onPostExecute(Object res) {
if (res instanceof Exception) {
int d = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(),""+res,d);
toast.show();
}
}
}.execute();
Another temporary 'workaround' is to set your android:targetSdkVersion="9" or below in AndroidManifest.xml, as this exception was introduced in API level 10.
Documentation on Android Developers is pretty rich on such an important topic. You'll get it through with that.
http://developer.android.com/reference/android/os/AsyncTask.html
You may want to refer the NetworkConnect sample from the Android SDK.

How do I post and retrieve tweets in an Android app?

I'm trying to make a Twitter app which includes posting and retrieving tweets from the user's timeline and setting it in a list view which also updates when someone tweets.
I also wish to allow the user to upload photos to Twitter.
Here's my code:
package com.example.listtweetdemo;
import java.util.ArrayList;
import java.util.List;
import twitter4j.Paging;
import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import twitter4j.internal.org.json.JSONArray;
import twitter4j.internal.org.json.JSONObject;
import twitter4j.json.DataObjectFactory;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
private Button twitt;
private Button read;
private Button login;
private Button logout;
private EditText edt;
private boolean man = true;
private TextView textName;
private ListView list;
List<Status> statuses = new ArrayList<Status>();
static final String consumerKey = "RVVVPnAUa8e1XXXXXXXXX";
static final String consumerSecretKey = "eCh0Bb12n9oDmcomBdfisKZIfJmChC2XXXXXXXXXXXX";
static final String prefName = "twitter_oauth";
static final String prefKeyOauthToken = "oauth_token";
static final String prefKeyOauthSecret = "oauth_token_secret";
static final String prefKeyTwitterLogin = "isTwitterLogedIn";
static final String twitterCallbackUrl = "oauth://t4jsample";
static final String urlTwitterOauth = "auth_url";
static final String urlTwitterVerify = "oauth_verifier";
static final String urlTwitterToken = "oauth_token";
static SharedPreferences pref;
private static Twitter twitter;
private static RequestToken reqToken;
private connectionDetector cd;
AlertDailogManager alert = new AlertDailogManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpIds();
cd = new connectionDetector(getApplicationContext());
if(!cd.isConnectivityToInternet())
{
alert.showAlert(MainActivity.this, "Internet Connection Error", "Please Connect to working Internet connection", false);
return;
}
if(consumerKey.trim().length() == 0 || consumerSecretKey.trim().length() == 0)
{
alert.showAlert(MainActivity.this, "Twitter Oauth Token", "Please set your Twitter oauth token first!", false);
return;
}
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
loginToTwitter();
}
});
logout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
logoutFromTwitter();
}
});
read.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Paging paging = new Paging(200); // MAX 200 IN ONE CALL. SET YOUR OWN NUMBER <= 200
try {
statuses = twitter.getHomeTimeline();
} catch (TwitterException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
String strInitialDataSet = DataObjectFactory.getRawJSON(statuses);
JSONArray JATweets = new JSONArray(strInitialDataSet);
for (int i = 0; i < JATweets.length(); i++) {
JSONObject JOTweets = JATweets.getJSONObject(i);
Log.e("TWEETS", JOTweets.toString());
}
} catch (Exception e) {
// TODO: handle exception
}
/*try {
ResponseList<Status> statii = twitter.getHomeTimeline();
statusListAdapter adapter = new statusListAdapter(getApplicationContext(), statii);
setListAdapter(adapter);
Log.d("HOME TIMELINE", statii.toString());
} catch (TwitterException e) {
e.printStackTrace();
}
//list.setVisibility(View.VISIBLE);
read.setVisibility(View.GONE);*/
}
});
twitt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String status = edt.getText().toString();
if(status.trim().length() > 0)
{
new updateTwitter().execute(status);
}
}
});
if(!isTwitterLogedInAlready())
{
Uri uri = getIntent().getData();
if(uri != null && uri.toString().startsWith(twitterCallbackUrl))
{
String verify = uri.getQueryParameter(urlTwitterVerify);
try
{
AccessToken accessToken = twitter.getOAuthAccessToken(reqToken,verify);
Editor edit = pref.edit();
edit.putString(prefKeyOauthToken, accessToken.getToken());
edit.putString(prefKeyOauthSecret, accessToken.getTokenSecret());
edit.putBoolean(prefKeyTwitterLogin, true);
edit.commit();
Log.d("Twitter oauth Token", ">" + accessToken.getToken());
login.setVisibility(View.INVISIBLE);
twitt.setVisibility(View.VISIBLE);
edt.setVisibility(View.VISIBLE);
read.setVisibility(View.VISIBLE);
textName.setVisibility(View.VISIBLE);
if(man == true)
{
logout.setVisibility(View.VISIBLE);
}
long userId = accessToken.getUserId();
User user = twitter.showUser(userId);
//User user = twitter.getHomeTimeline();
Status n = user.getStatus();
String userName = user.getName();
textName.setText(userName);
}
catch(Exception e)
{
Log.d("Twitter Login Error", ">" + e.getMessage());
}
}
}
}
private void setUpIds() {
twitt = (Button)findViewById(R.id.buttTwitt);
login = (Button)findViewById(R.id.buttLogin);
read = (Button)findViewById(R.id.buttRead);
edt = (EditText)findViewById(R.id.editText1);
logout = (Button)findViewById(R.id.buttLogout);
textName = (TextView)findViewById(R.id.textName);
//list = (ListView)findViewById(R.id.listView1);
pref = getApplicationContext().getSharedPreferences("myPref", 0);
}
protected void logoutFromTwitter() {
Editor e = pref.edit();
e.remove(prefKeyOauthSecret);
e.remove(prefKeyOauthToken);
e.remove(prefKeyTwitterLogin);
e.commit();
login.setVisibility(View.VISIBLE);
logout.setVisibility(View.GONE);
twitt.setVisibility(View.GONE);
edt.setVisibility(View.GONE);
read.setVisibility(View.GONE);
textName.setVisibility(View.GONE);
}
protected void loginToTwitter() {
if(!isTwitterLogedInAlready())
{
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecretKey);
builder.setJSONStoreEnabled(true);
builder.setIncludeEntitiesEnabled(true);
builder.setIncludeMyRetweetEnabled(true);
builder.setIncludeRTsEnabled(true);
Configuration config = builder.build();
TwitterFactory factory = new TwitterFactory(config);
twitter = factory.getInstance();
try{
reqToken = twitter.getOAuthRequestToken(twitterCallbackUrl);
this.startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(reqToken.getAuthenticationURL())));
}
catch(TwitterException e)
{
e.printStackTrace();
}
}
else
{
Toast.makeText(getApplicationContext(), "Already Logged In", Toast.LENGTH_LONG).show();
logout.setVisibility(View.VISIBLE);
man = false;
}
}
private boolean isTwitterLogedInAlready() {
return pref.getBoolean(prefKeyTwitterLogin, false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class updateTwitter extends AsyncTask<String , String, String>{
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to Twitter status..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
Log.d("Tweet Text", "> " + args[0]);
String status = args[0];
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecretKey);
// Access Token
String access_token = pref.getString(prefKeyOauthToken, "");
// Access Token Secret
String access_token_secret = pref.getString(prefKeyOauthSecret, "");
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
// Update status
twitter4j.Status response = twitter.updateStatus(status);
Log.d("Status", "> " + response.getText());
} catch (TwitterException e) {
// Error in updating status
Log.d("Twitter Update Error", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Status update successfully", Toast.LENGTH_SHORT).show();
edt.setText("");
}
});
}
}
}
Use the new Twitter Fabric SDK for Android. Requires sign up first. If you don't want to wait to be approved for the sign up, then I recommend using the following link
https://github.com/Rockncoder/TwitterTutorial
The link above explains how to retrieve tweets. You should be able to use the above link COMBINED with the information in the link below to POST tweets!
https://dev.twitter.com/overview/documentation

toast mesage not shown on screen when network or server not available

I need to show toast message when the server is not responding
when I press the login button, some parameters are passed to AgAppMenu screen which use url connection to server and get xml response in AgAppHelperMethods screen. The
probelm is when the server is busy or the network is not avaibale, I can't show toast message on catch block although it shows the log message.
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent ;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginScreen extends Activity implements OnClickListener {
EditText mobile;
EditText pin;
Button btnLogin;
Button btnClear;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.agapplogin);
TextView lblMobileNo = (TextView) findViewById(R.id.lblMobileNo);
lblMobileNo.setTextColor(getResources()
.getColor(R.color.text_color_red));
mobile = (EditText) findViewById(R.id.txtMobileNo);
TextView lblPinNo = (TextView) findViewById(R.id.lblPinNo);
lblPinNo.setTextColor(getResources().getColor(R.color.text_color_red));
pin = (EditText) findViewById(R.id.txtPinNo);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnClear = (Button) findViewById(R.id.btnClear);
btnLogin.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
postLoginData();
}
});
btnClear.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
cleartext();
}
});
/*
*
* btnClear.setOnClickListener(new OnClickListener() { public void
* onClick(View arg0) {
*
* } });
*/
}
public void postLoginData()
{
if (pin.getTextSize() == 0 || mobile.getTextSize() == 0) {
AlertDialog.Builder altDialog = new AlertDialog.Builder(this);
altDialog.setMessage("Please Enter Complete Information!");
} else {
Intent i = new Intent(this.getApplicationContext(), AgAppMenu.class);
Bundle bundle = new Bundle();
bundle.putString("mno", mobile.getText().toString());
bundle.putString("pinno", pin.getText().toString());
i.putExtras(bundle);
startActivity(i);
}
}
#Override
public void onClick(View v) {
}
public void cleartext() {
{
pin.setText("");
mobile.setText("");
}
}
}
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class AgAppMenu extends Activity {
String mno, pinno;
private String[][] xmlRespone;
Button btnMiniStatement;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agappmenu);
mno = getIntent().getExtras().getString("mno");
pinno = getIntent().getExtras().getString("pinno");
setTitle("Welcome to the Ag App Menu");
AgAppHelperMethods agapp =new AgAppHelperMethods();
// xmlRespone = AgAppHelperMethods.AgAppXMLParser("AG_IT_App/AgMainServlet?messageType=LOG&pin=" + pinno + "&mobile=" + mno + "&source=" + mno + "&channel=INTERNET");
xmlRespone = agapp.AgAppXMLParser("AG_IT_App/AgMainServlet?messageType=LOG&pin=" + pinno + "&mobile=" + mno + "&source=" + mno + "&channel=INTERNET");
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnKeyListener;
public class AgAppHelperMethods extends Activity {
private static final String LOG_TAG = null;
private static AgAppHelperMethods instance = null;
public static String varMobileNo;
public static String varPinNo;
String[][] xmlRespone = null;
boolean flag = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agapphelpermethods);
}
protected AgAppHelperMethods() {
}
public static AgAppHelperMethods getInstance() {
if (instance == null) {
instance = new AgAppHelperMethods();
}
return instance;
}
public static String getUrl() {
String url = "https://demo.accessgroup.mobi/";
return url;
}
public String[][] AgAppXMLParser(String parUrl) {
String _node, _element;
String[][] xmlRespone = null;
try {
String url = AgAppHelperMethods.getUrl() + parUrl;
URL finalUrl = new URL(url);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(finalUrl.openStream()));
doc.getDocumentElement().normalize();
NodeList list = doc.getElementsByTagName("*");
_node = new String();
_element = new String();
xmlRespone = new String[list.getLength()][2];
// this "for" loop is used to parse through the
// XML document and extract all elements and their
// value, so they can be displayed on the device
for (int i = 0; i < list.getLength(); i++) {
Node value = list.item(i).getChildNodes().item(0);
_node = list.item(i).getNodeName();
_element = value.getNodeValue();
xmlRespone[i][0] = _node;
xmlRespone[i][1] = _element;
}// end for
throw new ArrayIndexOutOfBoundsException();
}// end try
// will catch any exception thrown by the XML parser
catch (Exception e) {
Toast.makeText(AgAppHelperMethods.this,
"error server not responding " + e.getMessage(),
Toast.LENGTH_SHORT).show();
Log.e(LOG_TAG, "CONNECTION ERROR FUNDAMO SERVER NOT RESPONDING", e);
}
// Log.e(LOG_TAG, "CONNECTION ERROR FUNDAMO SERVER NOT RESPONDING", e);
return xmlRespone;
}
`
AgAppHelperMethods isn't really an Activity. You've derived this class from Activity, but then you've created Singleton management methods (getInstance()) and you are instantiating it yourself. This is bad. Don't do this.
Normally Android controls the instantiation of activities. You don't ever create one yourself (with new).
It looks to me like AgAppHelperMethods just needs to be a regular Java class. It doesn't need to inherit from anything. Remove also the lifecycle methods like onCreate().
Now you will have a problem with the toast, because you need a context for that and AgAppHelperMethods isn't a Context. To solve that you can add Context as a parameter to AgAppXMLParser() like this:
public String[][] AgAppXMLParser(Context context, String parUrl) {
...
// Now you can use "context" to create your toast.
}
When you call AgAppXMLParser() from AgAppMenu just pass "this" as the context parameter.

Categories

Resources