Android - Using a variable from another class? - java

I'm making an Android application wherein a student logs in with his registration ID then can access services like view his grades, class schedule, etc. without entering his registration ID twice.
My question here is, how can I get the registration ID he first entered during login and use it to access other activities so that he would not have to enter again?
Here's is the code for the login activity:
package com.example.kreshiathea.myfirstapp;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
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 MainActivity2 extends Activity {
Button b;
EditText et,pass;
TextView tv;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
b = (Button)findViewById(R.id.loginnext);
et = (EditText)findViewById(R.id.rfid);
tv = (TextView)findViewById(R.id.tv);
String rfid = et.getText().toString().trim();
Intent in = new Intent(getApplicationContext(), MainActivity3Activity.class);
in.putExtra("rfid", rfid);
startActivity(in);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog = ProgressDialog.show( MainActivity2.this, "",
"Validating user...", true);
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
}
});
}
void login(){
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://usamobileapp.pe.hu/webservice/check.php"); // make sure the url is correct.
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim())); // $Edittext_value = $_POST['Edittext_value'];
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response=httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
tv.setText("Response from PHP : " + response);
dialog.dismiss();
}
});
if(response.equalsIgnoreCase("User Found")){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText( MainActivity2.this,"Login Success", Toast.LENGTH_SHORT).show();
}
});
startActivity(new Intent( MainActivity2.this, MainActivity3Activity.class));
}else{
showAlert();
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
public void showAlert(){
MainActivity2.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder( MainActivity2.this);
builder.setTitle("Login Error.");
builder.setMessage("User not Found.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
}
I tried to uses an instance so I could import variable to another class. But I'm sure where to put it exactly so I placed it here:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
b = (Button)findViewById(R.id.loginnext);
et = (EditText)findViewById(R.id.rfid);
tv = (TextView)findViewById(R.id.tv);
String rfid = et.getText().toString().trim();
Intent in = new Intent(getApplicationContext(), MainActivity3Activity.class);
in.putExtra("rfid", rfid);
startActivity(in);
This is the class where I want to import the variable MainActivity3Activity
Here's the code:
package com.example.kreshiathea.myfirstapp;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity3Activity extends Activity {
Intent in = getIntent();
String rfid = in.getStringExtra("rfid");
HttpClient httpclient;
HttpGet request;
HttpResponse response;
HttpPost httppost;
List<NameValuePair> nameValuePairs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity3);
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://usamobileapp.pe.hu/webservice/student_info.php");
try {
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", rfid));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
TextView result = (TextView) findViewById(R.id.tvResult);
try {
request = new HttpGet("http://usamobileapp.pe.hu/webservice/student_info.php");
response = httpclient.execute(request);
} catch (Exception e) {
e.printStackTrace();
}
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
I place the receiving intent here:
public class MainActivity3Activity extends Activity {
Intent in = getIntent();
String rfid = in.getStringExtra("rfid");
HttpClient httpclient;
HttpGet request;
HttpResponse response;
HttpPost httppost;
List<NameValuePair> nameValuePairs;
The MainActivity3Activity class also displays the student information (using the previously entered registration ID).
I'm not sure if I correctly used and placed the intents. So please I'm looking for any help.

Call getIntent(); method to receive Intent from previous Activity in onCreate method of MainActivity3Activity Activity like :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent in = getIntent();
String rfid = in.getStringExtra("rfid");
}

You should move
Intent in = getIntent();
String rfid = in.getStringExtra("rfid");
inside onCreate(...) method of Activity
getIntent() is available only after onCreate(...) you cant used it before onCreate(...)

Use sharedpreferences if you want to use in multiple activities
SharedPreferences preferences=getSharedPreferences("logindetails", Activity.MODE_PRIVATE);
Editor editor=preferences.edit();
editor.putString("regId", id);
editor.commit();
You can get regid as follows
id=getSharedPreferences("logindetails", Activity.MODE_PRIVATE).getString("regId",defaultValue);
Hope this will help you.

Intent intent = getIntent();
String id = intent.getStringExtra("regId");
Using this id you can get all the details in the next activity.

You could store the registration as a static variable, which means it will maintain its value and you can access it from anywhere. I've done this loads of times in my own code and it's really handy.
For example, you could create a class called Globals or something, and in this class have your registration number.
public class Globals {
public static String registrationNumber;
// Or make a nice getter and setter for this :)
}
...so when you get the number from the user's input, set this variable:
Globals.registrationNumber = registrationNumber;
...then get it from this class when you need it later:
String registrationNumber = Globals.registrationNumber;
It's best to only use this for small things like this. If you keep massive objects in static variables, it means that object will continue to use memory throughout your app's lifecycle. Unless you are using something often, or the object is small (like your reg number), I wouldn't do this, as it is an unnecessary use of memory.
The other answers about passing the registration number between activities via the Intent is just as good an approach. It just means you have to write and read the value from the Intent extras every time. I would personally use that approach for passing an object or ID of something you have selected from a list to display it in a detail screen or something. For something that you regularly use, I'd go for the static variable approach.
Also... another thing you could do is save the registration number in the app preferences so that you can read it when the user starts the app and they don't have to log in again.
// Save the registration number to preferences.
SharedPreferences preferences = context.getSharedPreferences("MY_APP_PREFERENCES", Context.MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putString("REGISTRATION_NUMBER", registrationNumber);
editor.commit();
...
// Get from preferences.
SharedPreferences preferences = context.getSharedPreferences("MY_APP_PREFERENCES", Context.MODE_PRIVATE);
String registrationNumber = preferences.getString("REGISTRATION_NUMBER", null);
// The second parameter above is the default value if nothing is returned.
Good luck!

Related

sending data from device to remote server

My application is passing two value from device to remote server but it work in when i tested in bluestack when I install in real device it show a message like "Unfortunately app has been stooped" so I can't under stand where is problem i delete and clean device temporary and cache memory of device still not getting output.
following is my source code
package com.androidexample.httpgetexample;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class HttpGetAndroidExample extends Activity {
TextView content;
EditText fname,email,login,pass;
Spinner sp;
Button b1;
String s[] = { "Courtage Problem", "Cartage Refil", "Printer Problem",
"Printer Drivers" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_http_get_android_example);
content = (TextView)findViewById(R.id.content);
fname = (EditText)findViewById(R.id.name);
sp = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> ad = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, s);
sp.setAdapter(ad);
ad.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Button saveme=(Button)findViewById(R.id.save);
saveme.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v)
{
//ALERT MESSAGE
Toast.makeText(getBaseContext(),
"Please wait, connecting to server.",
Toast.LENGTH_LONG).show();
try{
String n = URLEncoder.encode(fname.getText().toString(), "UTF-8");
String d = URLEncoder.encode(sp.getSelectedItem().toString(), "UTF-8");
HttpClient Client = new DefaultHttpClient();
String URL = "http://shreebijapur.in/Customerquery.aspx?n="+n+"&d="+d;
//Log.i("httpget", URL);
try
{
HttpGet httpget = new HttpGet(URL);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String SetServerString = "";
SetServerString = Client.execute(httpget, responseHandler);
content.setText(SetServerString);
}
catch(Exception ex)
{
content.setText("Fail!");
}
}
catch(UnsupportedEncodingException ex)
{
content.setText("Fail111");
}
}
});
}
}
It's probably crashing due to the networkOnMainThreadException. I'm trying to executr an http request in an inner class that extends class AsyncTask.
I put all network related stuff in the doInBackground() method.
If Error: networkOnMainThreadException
Perform http request execution in an inner class that extends the class AsyncTask.
or
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// HERE_YOUR_HTTP_REQUEST CODE
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}.execute();
Try this
Or
You can use volley, retrofit or other networking library's for API call.

wrong loop is getting executed in case of valid user

I have an activity which validates a user by checking the credentials from the server.
Here is my code.
PaymentActivity.java
package com.example.androidphpmy;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
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 PaymentActivity extends Activity {
Button b;
EditText et,pass;
TextView tv;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment);
b = (Button)findViewById(R.id.Button01);
et = (EditText)findViewById(R.id.accountno);
pass= (EditText)findViewById(R.id.password);
tv = (TextView)findViewById(R.id.tv);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog = ProgressDialog.show(PaymentActivity.this, "",
"Validating user...", true);
new Thread(new Runnable() {
public void run() {
payment();
}
}).start();
}
});
}
void payment(){
try{
httpclient=new DefaultHttpClient();
httppost= new
HttpPost("http://tanushreedutta.site40.net/payment_new/check.php");
//add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
// Always use the same variable name for posting i.e the android side variable name and
php side variable name should be similar,
nameValuePairs.add(new
BasicNameValuePair("accno",et.getText().toString().trim()));
// $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new
BasicNameValuePair("bpassword",pass.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
// edited by James from coderzheaven.. from here....
ResponseHandler<String> responseHandler = new
BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
tv.setText("Response from PHP : " + response);
dialog.dismiss();
}
});
if(response.equalsIgnoreCase("User Found")){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(PaymentActivity.this,"Payment Successful",Toast.LENGTH_SHORT).show();
}
});
startActivity(new Intent(PaymentActivity.this, MainActivity.class));
}
else{
showAlert();
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
public void showAlert(){
PaymentActivity.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(PaymentActivity.this);
builder.setTitle("Payment Error.");
builder.setMessage("User not Found.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
}
Response generating php file
<?php
$hostname_localhost ="url";
$database_localhost ="databasename";
$username_localhost ="myusername";
$password_localhost ="xxxx";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
$accno = $_POST['accno'];
$bpassword = $_POST['bpassword'];
$query_search = "select * from details where accno = '".$accno."' AND bpassword =
'".$bpassword. "'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
//echo $rows;
if($rows == 0) {
echo "No Such User Found";
}
else {
echo "User Found";
}
?>
Now the problem is whenever I enter account no and password in response text it gives me correct output but in any of the cases (valid or invalid user) it executes "else" statement i.e executes showAlert() method. Is there any problem with my code.Any suggestion or advice will be highly appreciated. Thank you all in advance !
There's nothing complex going on here; your response is clearly just not saying "User Found"; so you should check that thoroughly.
Just attach your debugger, set a breakpoint at that line, and see what the response actually says in this case. It should be quite obvious what's amiss when you can pause there and step through/view the state of the various variables.
Alternately, you need to post the function that generates the response so we can see what it would return given your input. There isn't enough information here for us to fully diagnose the issue currently.

App not redirecting to next page after login

I made login page in my app, But i am getting problem when user input right user and pass it show on screen that User Found but app is not redirecting to next layout.
PHP code is:
<?php
$host="XXXXXXXXXXXXXX";
$username="aXXXXX62";
$password="XXXXXX";
$db_name="XXXXXn";
$tbl_name="mXXXXs";
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1){
echo "User Found";
session_register("myusername");
session_register("mypassword");
}
else {
echo "Wrong Username or Password";
}
?>
and here is my java code:
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
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 MainActivity extends Activity {
Button b,signup;
EditText myusername,mypassword;
TextView tv;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
b = (Button)findViewById(R.id.login);
signup = (Button) findViewById(R.id.signup);
myusername = (EditText)findViewById(R.id.username);
mypassword= (EditText)findViewById(R.id.password);
tv = (TextView)findViewById(R.id.tv);
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent( getBaseContext(), signup.class));
}
});
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog = ProgressDialog.show(MainActivity.this, "",
"Validating user...", true);
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
}
});
}
void login(){
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://getjobcompleted.info/checklogin.php");
//add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair("myusername",myusername.getText().toString().trim())); ;
nameValuePairs.add(new BasicNameValuePair("mypassword",mypassword.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
// edited by James from coderzheaven.. from here....
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
tv.setText("Response from PHP : " + response);
dialog.dismiss();
}
});
if(response.equalsIgnoreCase("User Found")){
startActivity(new Intent(getBaseContext(), view_create_url.class));
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
}
the APP show that user is authenticated but when but it is redirecting to the next page.
Please let me know what needs to be change?
You should get the entity from the response and create an input stream from it
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
Then read from the input stream and check for the response needed.

Connecting to MySQL database via Android SDK

Can any one please tell me where to find a simple tutorial that shows how to make an Android application that connects to a external MySQL database, and report back some data?
The tutorials I found on the Internet are not exact - they dont work or the code is not complete.
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
public class main extends Activity {
/** Called when the activity is first created. */
Button login;
String name = "", pass = "";
EditText username, password;
TextView tv;
byte[] data;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
InputStream inputStream;
SharedPreferences app_preferences;
List<NameValuePair> nameValuePairs;
CheckBox check;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login);
check = (CheckBox) findViewById(R.id.check);
String Str_user = app_preferences.getString("username", "0");
String Str_pass = app_preferences.getString("password", "0");
String Str_check = app_preferences.getString("checked", "no");
if (Str_check.equals("yes")) {
username.setText(Str_user);
password.setText(Str_pass);
check.setChecked(true);
}
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
name = username.getText().toString();
pass = password.getText().toString();
String Str_check2 = app_preferences.getString("checked", "no");
if (Str_check2.equals("yes")) {
SharedPreferences.Editor editor = app_preferences.edit();
editor.putString("username", name);
editor.putString("password", pass);
editor.commit();
}
if (name.equals("") || pass.equals("")) {
Toast.makeText(main.this, "Blank Field..Please Enter",
Toast.LENGTH_LONG).show();
} else {
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost(
"http://www.****.com/android/check.php");
// Add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserEmail",
name.trim()));
nameValuePairs.add(new BasicNameValuePair("Password",
pass.trim()));
httppost.setEntity(new UrlEncodedFormEntity(
nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
data = new byte[256];
buffer = new StringBuffer();
int len = 0;
while (-1 != (len = inputStream.read(data))) {
buffer.append(new String(data, 0, len));
}
inputStream.close();
} catch (Exception e) {
Toast.makeText(main.this, "error" + e.toString(),
Toast.LENGTH_LONG).show();
}
if (buffer.charAt(0) == 'Y') {
Toast.makeText(main.this, "login successfull",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(main.this,
"Invalid Username or password",
Toast.LENGTH_LONG).show();
}
}
}
});
check.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on clicks, depending on whether it's now
// checked
SharedPreferences.Editor editor = app_preferences.edit();
if (((CheckBox) v).isChecked()) {
editor.putString("checked", "yes");
editor.commit();
} else {
editor.putString("checked", "no");
editor.commit();
}
}
});
}
public void Move_to_next() {
// startActivity(new Intent(this, zzz.class));
}
}
I couldn't easily find a fully described example. But heres where i would start.
Look at content providers for managing your app data and accessing it and storing it for local use. The link below gives an extensive explanation of how content providers work. Though you don't have to use one.
http://www.satyakomatineni.com/akc/display?url=DisplayNoteIMPURL&reportId=2882&ownerUserId=satya
The android content provider example also shows this.
On your server at home look at providing a rest full service layer for your app to request the information from. Rather than perhaps trying to directly access the database iteself. Discussed to some extent here on what to do (not specifically how to do it) https://groups.google.com/forum/?fromgroups#!topic/android-developers/rzV9tYpQZ5Y%5B1-25%5D
Afraid i don't have coded examples.

unable to call method

I'm trying to implement ZXing barcode scanner into my program. After getting the scanned result, I wanted to parse the result to a method named getData() which belong to another Java class. No syntax error on IDE, but mysql.getData(contents) won't call the method no matter what. Please advise.
If I put this code under onCreate, the whole program force closed:
package com.posQR.ip;
import com.posQR.ip.MySQL;
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 PosQRActivity extends Activity{
MySQL mysql;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mysql.getData("productID");
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(scanListener);
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
TextView textView = (TextView)findViewById(R.id.textView1);
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
try {
String contents = intent.getStringExtra("SCAN_RESULT");
Toast.makeText(getApplicationContext(), contents + "from main", Toast.LENGTH_LONG).show();
mysql.getData(contents);
String string = Double.toString(mysql.getPrice());
textView.setText(string);
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Please scan on the product's QR Code.", Toast.LENGTH_LONG).show();
}
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
}
}
}
private OnClickListener scanListener = new OnClickListener() {
public void onClick(View v) {
try{
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
}
catch (Exception e){
Toast.makeText(getApplicationContext(), "error opening scanner.", Toast.LENGTH_SHORT).show();
}
}
};
}
.
package com.posQR.ip;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.net.ParseException;
import android.util.Log;
import android.widget.Toast;
public class MySQL{
double Price;
private Context localContext;
public void getData(String productID) {
InputStream is = null;
String result = "";
Toast.makeText(localContext.getApplicationContext(), productID, Toast.LENGTH_LONG).show();
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id",productID));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://dl.dropbox.com/u/11233767/mysqlRequest.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convert response to string
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(localContext.getApplicationContext(), "Error converting result.", Toast.LENGTH_LONG).show();
}
//paring data
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
json_data = jArray.getJSONObject(0);
Price=json_data.getDouble("price");
}
catch(JSONException e1){
Toast.makeText(localContext.getApplicationContext(), "No City Found" ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
}
public double getPrice(){
return Price;
}
}
There are many problems here, such as:
the mysql variable is null when you use it in onCreate, you must declare it.
The localContext object in MySql is never initialized, which will cause another NullPointerException when you call getData(). You should create a constructor that accepts a Context object for the MySql class, and use that constructor when you're fixing the first problem. Alternatively you could pass a Context object to getData()
the getData() method accesses the network in the main/UI thread, which will cause another Exception. Call this method in a different thread or spin off a new thread within the method itself. You may want to use an AsyncTask

Categories

Resources