I am trying to send data from an an Android app to a Servlet.
My Android Application is working properly.
The issue is only with the request sent to the Servlet. It gives error BasicNetwork.performRequest: Unexpected response code 500
Note: I am using Android Volley library to send my request to the Servlet.
Below I have mentioned:
1. My Android app code
2. My Servlet Code
3. LogCat
My Android App: MainActivity.java File
package com.example.hawk;
import java.util.HashMap;
import java.util.Map;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements View.OnClickListener {
EditText var_sp = null;
EditText var_ect = null;
EditText var_er = null;
EditText var_iat = null;
EditText var_atp = null;
Button submit;
RequestQueue rq = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
v1 = (EditText) findViewById(R.id.sp);
v2 = (EditText) findViewById(R.id.ect);
v3 = (EditText) findViewById(R.id.er);
v4 = (EditText) findViewById(R.id.iat);
v5 = (EditText) findViewById(R.id.atp);
submit = (Button) findViewById(R.id.submit);
rq=Volley.newRequestQueue(this);
submit.setOnClickListener(this);
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.submit:
new Thread(new Runnable() {
public void run() {
try{
StringRequest postReq = new StringRequest(Request.Method.POST, "http://192.168.0.103:8080/ServletABC",new Response.Listener<String>() {
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("var1",v1.getText().toString());
params.put("var2",v2.getText().toString());
params.put("var3",v3.getText().toString());
params.put("var4",v4.getText().toString());
params.put("var5",v5.getText().toString());
return params;
}
#Override
public void onResponse(String response) {
// TODO Auto-generated method stub
}
}, null);
rq.add(postReq);
}catch(Exception e)
{
e.printStackTrace();
}
}
}).start();
break;
}
}
}
My Servlet:
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class OBD_Feeder extends HttpServlet{
// JDBC driver name and database URL
public static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
public static final String DB_URL="jdbc:mysql://localhost/Test";
// Database credentials
public static final String USER ="xxxx";
public static final String PASS ="xxxx";
Connection conn;
Statement stmt;
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
double v1=Double.parseDouble(request.getParameter("var1"));
double v2=Double.parseDouble(request.getParameter("var2"));
double v3=Double.parseDouble(request.getParameter("var3"));
double v4=Double.parseDouble(request.getParameter("var4"));
double v5=Double.parseDouble(request.getParameter("var5"));
Calendar calendar = Calendar.getInstance();
java.sql.Timestamp today_ts = new java.sql.Timestamp(calendar.getTime().getTime());
//System.out.println("TimeStamp: "+today_ts);
try{
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Open a connection
conn =DriverManager.getConnection(DB_URL,USER,PASS);
// Execute SQL query
stmt = conn.createStatement();
PreparedStatement pst =(PreparedStatement) conn.prepareStatement("insert into obd_test1(speed,coolant_temp,engine_rpm,in_air_temp,throttle_position, time_stamp) values(?,?,?,?,?,?)");
pst.setDouble(1,v1);
pst.setDouble(2,v2);
pst.setDouble(3,v3);
pst.setDouble(4,v4);
pst.setDouble(5,v5);
pst.setTimestamp(6,today_ts);
System.out.println("DB Query: "+pst.toString());
//Query execution
int i = pst.executeUpdate();
//conn.commit();
String msg=" ";
if(i!=0){msg="Record has been inserted";}
else{msg="failed to insert the data";}
System.out.println("DB Transaction Status: "+msg);
String docType ="<!doctype html public \"-//w3c//dtd html 4.0 "+"transitional//en\">\n";
out.println(docType +
"<html>\n"+
"<head><title>OBD Feeder</title></head>\n"+
"<body bgcolor=\"#f0f0f0\">\n"+
"<h1 align=\"center\">DATA Received:</h1>\n"+
"<ul>\n"+msg+"</ul>\n"+
"</body></html>");
pst.close();
stmt.close();
conn.close();
}catch(SQLException se){ se.printStackTrace();}//Handle errors for JDBC se.printStackTrace();
catch(Exception e){ e.printStackTrace();}//Handle errors for Class.forName e.printStackTrace();
finally
{ //finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){ se2.printStackTrace();}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){ se.printStackTrace();
}//end finally try
}
}
}
My LogCat:
08-15 10:42:55.128: I/HAWK(29403): POST Request: [ ] http://192.168.0.102:8080/OBD_Feeder 0x85adf656 NORMAL 3
08-15 10:42:55.408: E/Volley(29403): [1056] BasicNetwork.performRequest: Unexpected response code 500 for http://192.168.0.102:8080/ServletABC
08-15 10:42:55.408: D/HAWK(29403): Error: null
08-15 10:44:56.648: W/IInputConnectionWrapper(29403): getTextBeforeCursor on inactive InputConnection
Check if you are using correct SDK
For Android Studio / IntelliJIDEA:
File -> Project Structure -> Project -> Project SDK
Modules -> Check each modules "Module SDK"
Preferably, you should use "Google API (x.x)" instead of Android API
Use the IP 10.0.2.2.
"192.168.0.103:8080/ServletABC" to
"10.0.2.2:8080/ServletABC"
Related
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);
}
}
}
Getting into android and have been trying to follow the following tutorial for a weather app udated with the OpenWeatherMap api http://code.tutsplus.com/tutorials/create-a-weather-app-on-android--cms-21587
I'm currently having trouble with the following class; the JSON object returned when the getJSON() method is called is always null resulting in no weather displayed. The URL works and I'm not sure what I'm doing wrong; I think I may have some kind of issue with the connection.addRequestProperty line. I am not sure if the API key is actually required for this JSON parse, as you can get the results in your browser without it eg. http://api.openweathermap.org/data/2.5/weather?q=London&units=metric
If anyone has any insight into where I am going wrong it would be very much appreciated!
EDIT: if anyone needs to see the rest of the package it is all currently identical to the code contained in the link posted.
EDIT 2: added the logcat created after dieter_h's suggested changes, thanks man.
LOGCAT:
08-20 23:20:55.219 12169-12169/? I/art﹕ Late-enabling -Xcheck:jni
08-20 23:20:55.587 12169-12191/simpleweather.ockmore.will.simpleweather D/OpenGLRenderer﹕ Use EGL_SWAP_BEHAVIOR_PRESERVED: true
08-20 23:20:55.598 12169-12169/simpleweather.ockmore.will.simpleweather D/Atlas﹕ Validating map...
08-20 23:20:55.659 12169-12188/simpleweather.ockmore.will.simpleweather I/myActivity﹕ data{"cod":"404","message":"Error: Not found city"}
08-20 23:20:55.671 12169-12191/simpleweather.ockmore.will.simpleweather I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_LA.AF.1.1_RB1.05.00.02.006.020_msm8960_LA.AF.1.1_RB1__release_AU ()
OpenGL ES Shader Compiler Version: E031.25.03.06
Build Date: 03/30/15 Mon
Local Branch: mybranch8688311
Remote Branch: quic/LA.AF.1.1_rb1.16
Local Patches: NONE
Reconstruct Branch: AU_LINUX_ANDROID_LA.AF.1.1_RB1.05.00.02.006.020 + 9b2699f + 2215637 + 60aa592 + f2362e6 + 5c64f59 + 82411a1 + 1f36e07 + NOTHING
08-20 23:20:55.673 12169-12191/simpleweather.ockmore.will.simpleweather I/OpenGLRenderer﹕ Initialized EGL, version 1.4
08-20 23:20:55.707 12169-12191/simpleweather.ockmore.will.simpleweather D/OpenGLRenderer﹕ Enabling debug mode 0
08-20 23:20:55.809 12169-12169/simpleweather.ockmore.will.simpleweather E/SimpleWeather﹕ One or more fields not found in JSON data
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
import android.content.Context;
import android.util.Log;
public class RemoteFetch {
public static JSONObject getJSON(Context context, String city){
try {
URL url = new URL("http://api.openweathermap.org/data/2.5/weather?q=" +city+ "&units=metric");
HttpURLConnection connection =
(HttpURLConnection)url.openConnection();
connection.addRequestProperty("x-api-key",
context.getString(R.string.open_weather_maps_app_id));
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
StringBuilder json = new StringBuilder(1024);
String tmp=" ";
while ((tmp=reader.readLine())!=null)
json.append(tmp).append("\n");
reader.close();
JSONObject data = new JSONObject(json.toString());
//This value will be 404 if the request was not
//successful
if (data.getInt("cod")!=200){
return null;
}
return data;
}catch(Exception e) {
return null;
}
}
}
EDIT 3: Fragment and Activity classes added below
import android.graphics.Typeface;
import android.os.Bundle;
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.TextView;
import android.widget.Toast;
import android.os.Handler;
import org.json.JSONObject;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
public class WeatherFragment extends Fragment{
Typeface weatherFont;
TextView cityField;
TextView updatedField;
TextView detailsField;
TextView currentTemperatureField;
TextView weatherIcon;
Handler handler;
public WeatherFragment(){
handler = new Handler();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_weather, container, false);
cityField = (TextView)rootView.findViewById(R.id.city_field);
updatedField = (TextView)rootView.findViewById(R.id.updated_field);
detailsField = (TextView)rootView.findViewById(R.id.details_field);
currentTemperatureField = (TextView)rootView.findViewById(R.id.current_temperature_field);
weatherIcon = (TextView)rootView.findViewById(R.id.weather_icon);
weatherIcon.setTypeface(weatherFont);
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
weatherFont = Typeface.createFromAsset(getActivity().getAssets(), "fonts/weather.ttf");
updateWeatherData(new CityPreference(getActivity()).getCity());
}
private void updateWeatherData(final String city){
new Thread(){
public void run(){
final JSONObject json = RemoteFetch.getJSON(getActivity(), city);
if (json == null){
handler.post(new Runnable(){
public void run(){
Toast.makeText(getActivity(),
getActivity().getString(R.string.place_not_found),
Toast.LENGTH_LONG).show();
}
});
} else {
handler.post(new Runnable(){
#Override
public void run() {
renderWeather(json);
}
});
}
}
}.start();
}
private void renderWeather(JSONObject json){
try {
cityField.setText(json.getString("name").toUpperCase(Locale.UK) +
"," +
json.getJSONObject("sys").getString("country"));
JSONObject details = json.getJSONArray("weather").getJSONObject(0);
JSONObject main = json.getJSONObject("main");
detailsField.setText(
details.getString("description").toUpperCase(Locale.UK) +
"\n" + "Humidity: " + main.getString("humidity") + "%" +
"\n" + "Pressure: " + main.getString("pressure") + "hPa");
currentTemperatureField.setText(
String.format("%.2f", main.getDouble("temp")) + " ℃");
DateFormat df = DateFormat.getDateInstance();
String updatedOn = df.format(new Date(json.getLong("dt")*1000));
updatedField.setText("Last update: " + updatedOn);
setWeatherIcon(details.getInt("id"),
json.getJSONObject("sys").getLong("sunrise") * 1000,
json.getJSONObject("sys").getLong("sunset") * 1000);
}catch (Exception e) {
Log.e("SimpleWeather", "One or more fields not found in JSON data");
}
}
private void setWeatherIcon(int actualId, long sunrise, long sunset){
int id = actualId / 100;
String icon = "";
if(actualId == 800){
long currentTime = new Date().getTime();
if (currentTime>=sunrise && currentTime<sunset) {
icon = getActivity().getString(R.string.weather_sunny);
} else {
icon = getActivity().getString(R.string.weather_clear_night);
}
} else {
switch (id) {
case 2 : icon = getActivity().getString(R.string.weather_thunder);
break;
case 3 : icon = getActivity().getString(R.string.weather_drizzle);
break;
case 7 : icon = getActivity().getString(R.string.weather_foggy);
break;
case 8 : icon = getActivity().getString(R.string.weather_cloudy);
break;
case 6 : icon = getActivity().getString(R.string.weather_snowy);
break;
case 5 : icon = getActivity().getString(R.string.weather_rainy);
break;
}
weatherIcon.setText(icon);
}
}
public void changeCity(String city){
updateWeatherData(city);
}
Formatting is a bit odd, sorry.
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.Fragment;
import android.widget.EditText;
public class WeatherActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weather);
if(savedInstanceState == null){
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new WeatherFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_weather, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.change_city) {
showInputDialog();
}
return false;
}
private void showInputDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Change city");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
changeCity(input.getText().toString());
}
});
builder.show();
}
public void changeCity(String city){
WeatherFragment wf = (WeatherFragment)getSupportFragmentManager()
.findFragmentById(R.id.container);
wf.changeCity(city);
new CityPreference(this).setCity(city);
}
}
Try this, Add this after while loop.
finally
{
try {
if (reader != null)
reader.close();
}// end try
catch (IOException ex)
{
}// end catch
}//end finally.
Change code and post your logcat:
JSONObject data = new JSONObject(json.toString());
Log.i("MyActivity", "data + " data);
[...]
return data;
}catch(Exception e) {
Log.e("MyActivity", "Exception", e.fillInStackTrace());
return null;
}
Please use addRequestProperty to setRequestProperty:
connection.setRequestProperty("x-api-key",
context.getString(R.string.open_weather_maps_app_id));
instead of:
connection.addRequestProperty("x-api-key",
context.getString(R.string.open_weather_maps_app_id));
I am trying to make an persistent login application which then read sms from my phone and sends them to the an api with meaage body as well as the date and sender information. How can I proceed for the same.
I have made the login app but persistent login like facebook and other applications is not working.
Here is my code for the login application:
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.util.ArrayList;
public class LoginActivity extends ActionBarActivity {
private EditText un,pw;
private Button sign;
private TextView msg;
private String resp, errorMsg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
un = (EditText) findViewById(R.id.et_Username);
pw = (EditText) findViewById(R.id.et_Password);
sign = (Button) findViewById(R.id.bt_SignIn);
msg = (TextView) findViewById(R.id.tv_error);
sign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/**
* According with the new StrictGuard policy, running long tasks
* on the Main UI thread is not possible So creating new thread
* to create and execute http operations
*/
new Thread(new Runnable() {
#Override
public void run() {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username",
un.getText().toString()));
postParameters.add(new BasicNameValuePair("password",
pw.getText().toString()));
String response = null;
try {
response = SimpleHttpClient
.executeHttpPost(
url,
postParameters);
String res = response.toString();
System.out.println(res);
resp = res.replaceAll("\\s+", "");
} catch (Exception e) {
e.printStackTrace();
errorMsg = e.getMessage();
}
}
}).start();
try {
Thread.sleep(1000);
/**
* Inside the new thread we cannot update the main thread So
* updating the main thread outside the new thread
*/
msg.setText(resp);
if (null != errorMsg && !errorMsg.isEmpty()) {
msg.setText(errorMsg);
}
} catch (Exception e) {
msg.setText(e.getMessage());
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I tried this now,got the idea for shred prefernece but somewhow its not working for me
I tried this it doesn't show my main activity:
Can you find the problem:
MainActivity:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.util.ArrayList;
public class MainActivity extends Activity {
private String resp, errorMsg;
private EditText username,password;
/*public static final String MyPREFERENCES = "MyPrefs" ;
public static final String name = "nameKey";
public static final String pass = "passwordKey";
SharedPreferences sharedpreferences;*/
SessionManager session;
private TextView msg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText)findViewById(R.id.editText1);
password = (EditText)findViewById(R.id.editText2);
msg = (TextView) findViewById(R.id.tv_error);
session = new SessionManager(this);
}
#Override
protected void onResume() {
//sharedpreferences=getSharedPreferences(MyPREFERENCES,
// Context.MODE_PRIVATE);
if (session.getuser()!=null)
{
if(session.getpassword()!=null){
Intent i = new Intent(this,
Welcome.class);
startActivity(i);
}
}
super.onResume();
}
public void login(View view){
String u = username.getText().toString();
String p = password.getText().toString();
{
/**
* According with the new StrictGuard policy, running long tasks
* on the Main UI thread is not possible So creating new thread
* to create and execute http operations
*/
new Thread(new Runnable() {
#Override
public void run() {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username",
username.getText().toString()));
postParameters.add(new BasicNameValuePair("password",
password.getText().toString()));
String response = null;
try {
response = SimpleHttpClient
.executeHttpPost(
"<url>",
postParameters);
String res = response.toString();
//System.out.println(res);
resp = res.replaceAll("\\s+", "");
} catch (Exception e) {
e.printStackTrace();
errorMsg = e.getMessage();
}
}
}).start();
try {
Thread.sleep(1000);
/**
* Inside the new thread we cannot update the main thread So
* updating the main thread outside the new thread
*/
msg.setText(resp);
if (null != errorMsg && !errorMsg.isEmpty()) {
msg.setText(errorMsg);
}
} catch (Exception e) {
msg.setText(e.getMessage());
}
}
if (resp.contains("false")) {
session.saveSession(u, p);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
Welcome:
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
public class Welcome extends Activity {
SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
session = new SessionManager(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//. getMenuInflater().inflate(R.menu, menu);
return true;
}
public void logout(View view){
session.logoutUser();
moveTaskToBack(true);
Welcome.this.finish();
}
public void exit(View view){
moveTaskToBack(true);
Welcome.this.finish();
}
public List<Sms> getAllSms() {
List<Sms> lstSms = new ArrayList<Sms>();
Sms objSms = new Sms();
Uri message = Uri.parse("content://sms/inbox");
ContentResolver cr = this.getContentResolver();
Cursor c = cr.query(message, null, null, null, null);
this.startManagingCursor(c);
int totalSMS = c.getCount();
if (c.moveToFirst()) {
for (int i = 0; i < totalSMS; i++) {
if(c.getString(c.getColumnIndexOrThrow("address")).contains("icicib")|| c.getString(c.getColumnIndexOrThrow("address")).contains("hdfcbk") || c.getString(c.getColumnIndexOrThrow("address")).contains("dbalrt")
||c.getString(c.getColumnIndexOrThrow("address")).contains("citibk")||c.getString(c.getColumnIndexOrThrow("address")).contains("unionb")||c.getString(c.getColumnIndexOrThrow("address")).contains("atmsbi")
|| c.getString(c.getColumnIndexOrThrow("address")).contains("sbiinb") || c.getString(c.getColumnIndexOrThrow("address")).contains("indusb") ||c.getString(c.getColumnIndexOrThrow("address")).contains("fedbnk")
|| c.getString(c.getColumnIndexOrThrow("address")).contains("kotakb")||c.getString(c.getColumnIndexOrThrow("address")).contains("axisbk")||c.getString(c.getColumnIndexOrThrow("address")).contains("pnbsms")
|| c.getString(c.getColumnIndexOrThrow("address")).contains("hsbcin") || c.getString(c.getColumnIndexOrThrow("address")).contains("canbnk") || c.getString(c.getColumnIndexOrThrow("address")).contains("idbi")
||c.getString(c.getColumnIndexOrThrow("address")).contains("iob") || c.getString(c.getColumnIndexOrThrow("address")).contains("citibk") || c.getString(c.getColumnIndexOrThrow("address")).contains("hdfcbk")
||c.getString(c.getColumnIndexOrThrow("address")).contains("fromsc") ||c.getString(c.getColumnIndexOrThrow("address")).contains("myamex") || c.getString(c.getColumnIndexOrThrow("address")).contains("26463872")
|| c.getString(c.getColumnIndexOrThrow("address")).contains("sbicrd") || c.getString(c.getColumnIndexOrThrow("address")).contains("icici?") || c.getString(c.getColumnIndexOrThrow("address")).contains("syndbk")
|| c.getString(c.getColumnIndexOrThrow("address")).contains("121") || c.getString(c.getColumnIndexOrThrow("address")).contains("best deal(121)") || c.getString(c.getColumnIndexOrThrow("address")).contains("airtel")
|| c.getString(c.getColumnIndexOrThrow("address")).contains("vfcare") || c.getString(c.getColumnIndexOrThrow("address")).contains("vodafone") || c.getString(c.getColumnIndexOrThrow("address")).contains("mytsky")||c.getString(c.getColumnIndexOrThrow("address")).contains("dishpy") ) {
objSms = new Sms();
objSms.setAddress(c.getString(c .getColumnIndexOrThrow("address")));
objSms.setMsg(c.getString(c.getColumnIndexOrThrow("body")));
objSms.setTime(c.getString(c.getColumnIndexOrThrow("date")));
lstSms.add(objSms);
}
c.moveToNext();
}
}
// else {
// throw new RuntimeException("You have no SMS");
// }
c.close();
return lstSms;
}
}
SessionManager:
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
public class SessionManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
int PRIVATE_MODE = 0;
private static final String PREFER_NAME = "AndroidExamplePref";
public static final String KEY_USER = "username";
public static final String KEY_PWD = "password";
public SessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void saveSession(String user, String pwd){
editor.putString(KEY_USER, user);
editor.putString(KEY_PWD, pwd);
editor.commit();
}
public String getuser()
{
String s = pref.getString(KEY_USER,"");
return s;
}
public String getpassword()
{
String p = pref.getString(KEY_PWD,"");
return p;
}
public void logoutUser(){
editor.clear();
editor.commit();
Intent i = new Intent(_context,.MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
_context.startActivity(i);
}
}
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package=".sample" >
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.read_sms" />
<uses-permission android:name="android.permission.SEND_SMS" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Welcome"
android:label="#string/title_activity_welcome" >
</activity>
</application>
</manifest>
UPDATED ANSWER:
IT works now
i made session as static and before logging I am checking the shared preference value and accordingly going ahead. Everything is working now.
I guess you are meaning "persistent login application" -> User will log in once & for the next time they will not need to log in again with user name & password, right?
For this the naive approach would be storing the username & password in shared preference / db. But its not a good approach as it stores the password.
Instead of doing this, you can store, the userId/access token (obtained from the response). You should also have an expiration time so that you can prompt for log in validating the userId/access token after certain time.
Facebook seems to do the same thing I guess. E.g. if you clear data from on facebook app, then you does need to log in again.
I hope this gives you a direction.
Updated Answer
I guess you are not clear about pref.getString() method. The overloaded method (with 2 param) will return the 2nd param you sent, if any value with the query KEY (the 1st param)is not found.
In your case, in
public String getuser()
{
String s = pref.getString(KEY_USER,""); // here is the error, "" is not null, its an empty String.
return s;
}
So you can change this trouble causing line into either of the following line-
String s = pref.getString(KEY_USER,null);
or
String s = pref.getString(KEY_USER);
Same problem in the getuser(). Hopefully this will solve your problem :)
I'm trying to make a client in Android. This clients runs a thread that creates the client socket and launches another thread that is always listening to the socket to receive Strings. Everything is OK when I send a String from the client to a Java server running in a PC, but when I send a String from the server to the Android client the app finishes. Why do I get this error?
Here is the code of the main Activity of the client:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView chatHistorial;
EditText msg;
Socket client;
DataInputStream in;
DataOutputStream out;
Boolean cerrar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread t = new Thread(new Runnable(){
#Override
public void run() {
try{
client = new Socket("192.168.1.33", 4444);
in = new DataInputStream(client.getInputStream());
out = new DataOutputStream(client.getOutputStream());
cerrar = false;
chatHistorial = (TextView) findViewById(R.id.chatHistorial);
msg = (EditText) findViewById(R.id.msg);
ThreadLectura tl = new ThreadLectura(in, cerrar, chatHistorial);
tl.start();
}
catch(Exception e){
// ...
}
}
});
t.start();
findViewById(R.id.enviar).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String cadena = msg.getText().toString();
try {
out.writeUTF(cadena);
} catch (IOException e) {
// ...
}
if(cadena.equals("exit"))
cerrar = true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
class ThreadLectura extends Thread{
DataInputStream in;
String cadena;
TextView chatHistorial;
Boolean cerrar;
public ThreadLectura(DataInputStream in, Boolean cerrar, TextView tv){
this.in = in;
this.cerrar = cerrar;
chatHistorial = tv;
}
#Override
public void run(){
try{
while(!cerrar){
cadena = in.readUTF();
chatHistorial.append("Has recibido: " + cadena);
}
}
catch(IOException ioe){
System.out.println("Error de entrada/salida: "+ioe.getMessage());
}
}
}
It's hard to say without seeing your logcat output, but I'm betting it's because you are attempting to modify the UI from within your background thread. This line within ThreadLectura:
chatHistorial.append("Has recibido: " + cadena);
is probably the issue, as chatHistorial is a TextView. You need to only modify the UI from within the main UI thread.
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.