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
Related
I have created a application for connecting the PHP, Mysql & Android. I am inserting the Name , Price & Description. Layout is good, ids given perfect but the data is not inserting into SQL DB.
package com.oplo.user.demo2;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
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.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/**
* Created by user on 6/2/2015.
*/
#SuppressWarnings("deprecation")
public class addRecord extends Activity {
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
if(android.os.Build.VERSION.SDK_INT > 9)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
final EditText txtA = (EditText) findViewById(R.id.txtA);
final EditText txtB = (EditText) findViewById(R.id.txtB);
final EditText txtC = (EditText) findViewById(R.id.txtC);
final Button getData = (Button) findViewById(R.id.btnSave);
final Button btnBack = (Button) findViewById(R.id.btnBack);
btnBack.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
getData.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(txtA.getText().length()<2){
Toast.makeText(getApplicationContext(), "Input Name", Toast.LENGTH_LONG).show();
}if(txtB.getText().length()<2){
Toast.makeText(getApplicationContext(), "Input Price", Toast.LENGTH_LONG).show();
}if(txtC.getText().length()<2){
Toast.makeText(getApplicationContext(), "Input Description", Toast.LENGTH_LONG).show();
}else{
String url = "http://www.xyz.in/demo.php";
List params = new ArrayList();
//noinspection deprecation
params.add(new BasicNameValuePair("strA", txtA.getText().toString()));
params.add(new BasicNameValuePair("strB", txtB.getText().toString()));
params.add(new BasicNameValuePair("strC", txtC.getText().toString()));
#SuppressWarnings("unused")
String resultServer = getHttpPost(url,params);
//result.setText(resultServer);
Toast.makeText(addRecord.this, "1 Record inserted...", Toast.LENGTH_LONG).show();
emtyText();
txtA.requestFocus();
}
}
public void emtyText(){
txtA.setText("");
txtB.setText("");
txtC.setText("");
}
});
}
public String getHttpPost(String url,List params) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
}
PHP Code:
<?php
$host = "localhost";
$user = "xcxc";
$pass = "xcxc";
$database = "xcxc";
$con = mysql_connect($host, $user, $pass) or die("Cannot connect Database");
mysql_select_db($database) or die("Cannot select Database.");
$a = $_POST["strA"];
$b = $_POST["strB"];
$c = $_POST["strC"];
$sql = "INSERT INTO demo (name, price, description) VALUES('$a', '$b', '$c')";
$result = mysql_query("SET NAMES 'UTF8'", $con);
$result = mysql_query($sql, $con);
if(!$result){
die ('Error: '.mysql_error($con));
}
//echo "1 record added...";
mysql_close($con);
Heres my code, but the data is not inserting into SQL.
Please let me know wheres the problem in this code.
thanks in advance.
You are not allowed to do any network related stuff on your main thread,go for asynctask or retrofit.
this link may help
http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/
I am developing a app which insert data to MySQL data through PHP.
Everything seems Ok. But main problem is The data which i insert
goes blank to MySQL database.
Here is my code ......
1) This is my PHP file named insert.php
<?php
$host='my ip address';
$uname='user';
$pwd='password';
$db="user";
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
//$party=$_POST['party'];
//$code=$_POST['code'];
//$emply=$_POST['emply'];
//$date=$_POST['date'];
//echo $code+' '+'aaa';
mysql_query("INSERT INTO myapp(party,code,emply,date) VALUES('$_REQUEST[party]','$_REQUEST[code]','$_REQUEST[emply]','$_REQUEST[date]') ");
//mysql_query("insert into myapp(code) values($code)");
mysql_close($con);
?>
This in "//" blocked means i tried to that
2) This is my java code using (Android Studio)
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.InputType;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
import org.apache.http.HttpEntity;
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.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class MainActivity extends Activity {
protected static final String PrgUpdate = null;
Button mysql;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Button mysql = (Button)findViewById(R.id.mysql);
InputStream is = null;
mysql.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String party="Abhisheck";
String code="All update";
String emply="Bhavasar";
String date="01/04/2014";
List<NameValuePair> nameValuePair= new ArrayList<NameValuePair>(1);
nameValuePair.add(new BasicNameValuePair("party",party));
nameValuePair.add(new BasicNameValuePair("code",code));
nameValuePair.add(new BasicNameValuePair("emply",emply));
nameValuePair.add(new BasicNameValuePair("date",date));
System.out.println(nameValuePair.toString());
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://youripaddress.com/insert.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
Toast.makeText(getApplicationContext(),"Data enter succesful",Toast.LENGTH_SHORT).show();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
Log.e("ClientProtocolException","Client");
e.printStackTrace();
} catch (IOException e) {
Log.e("Ioexception","Ioexption");
e.printStackTrace();
}
}
});
}
Don't Worry About """"Date (Field)""""" it is character field.
My database mysql is here
Name Type Collation Attributes Null Default
1 id int(6) UNSIGNED No None AUTO_INCREMENT
2 party char(50) latin1_swedish_ci Yes NULL
3 code varchar(50) latin1_swedish_ci Yes NULL
4 emply varchar(50) latin1_swedish_ci Yes NULL
5 date char(50) latin1_swedish_ci Yes NULL
Now What the actual problem.
Why records not insert in MySQL.
Insert is the class which inserts the data in the database asynchronously. You can call the class by calling the execute() method. You need to override the doInBackground() method of AsyncTask.
You can find more details in the documentation over here: AsyncTask
class Insert extends AsyncTask<String, String, String>
{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String party="Abhisheck";
String code="All update";
String emply="Bhavasar";
String date="01/04/2014";
List<NameValuePair> nameValuePair= new ArrayList<NameValuePair>(1);
nameValuePair.add(new BasicNameValuePair("party",party));
nameValuePair.add(new BasicNameValuePair("code",code));
nameValuePair.add(new BasicNameValuePair("emply",emply));
nameValuePair.add(new BasicNameValuePair("date",date));
System.out.println(nameValuePair.toString());
try
{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.2.2/insert.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
//Toast.makeText(getApplicationContext(),"Data enter succesful",Toast.LENGTH_SHORT).show();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
Log.e("ClientProtocolException","Client");
e.printStackTrace();
} catch (IOException e) {
Log.e("Ioexception","Ioexption");
e.printStackTrace();
}
return null;
}
}
public class MainActivity extends Activity {
protected static final String PrgUpdate = null;
Button mysql;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Button mysql = (Button)findViewById(R.id.mysql);
ProgressDialog dialog;
InputStream is = null;
mysql.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Insert().execute();
}
});
}
}
Use this inside doInbackground()
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
});
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!
I'm scratching my head at this problem that I can't seem to figure out. What I'm trying to do is extract the URL following the HTTPpost. This will allow me to go through the Oauth process.
Currently I'm extracting the whole website into my entity.
For example: The data will be posted to https://mysite.com/login and will redirect after the post to https://mysite.com/dashboard?code=3593085390859082093720
How does one extract the url?
If you need any more information or can direct me in the right direction, all is appreciated! Thank you!
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
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.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.content.Intent;
import android.os.Bundle;
import android.util.Log;
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 LoginActivity extends Activity implements OnClickListener {
Button ok,back,exit;
TextView result;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
// Login button clicked
ok = (Button)findViewById(R.id.submit);
ok.setOnClickListener(this);
result = (TextView)findViewById(R.id.result);
}
public void postLoginData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://mysite.com/login");
try {
// Add user name and password
EditText uname = (EditText)findViewById(R.id.username);
String username = uname.getText().toString();
EditText pword = (EditText)findViewById(R.id.password);
String password = pword.getText().toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("pseudonym_session[unique_id]", username));
nameValuePairs.add(new BasicNameValuePair("pseudonym_session[password]", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
Log.w("CANVAS", "Execute HTTP Post Request");
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent()).toString();
Log.w("CANVAS", str);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String ResponseBody = httpclient.execute(httppost, responseHandler);
Intent intent = new Intent(getBaseContext(), DashboardActivity.class);
startActivity(intent);
if(str.toString().equalsIgnoreCase("true"))
{
Log.w("CANVAS", "TRUE");
result.setText("Login successful");
}else
{
Log.w("CANVAS", "FALSE");
result.setText(ResponseBody);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
#Override
public void onClick(View view) {
if(view == ok){
postLoginData();
}
}
}
if you set a redirect handler, you can get back from the response the location the server's sending you to. here's a snippet of code I was just playing with... (and I should point out, if you DON'T set a redirect handler, you'll just get redirected to the final destination, which might be the login screen itself)
DefaultHttpClient htc = getHttpClient();
htc.setRedirectHandler(new RedirectHandler() {
#Override
public boolean isRedirectRequested(HttpResponse response, HttpContext context)
{
Log.d(TAG, "isRedirectRequested, response: " + response.toString());
return false;
}
#Override
public URI getLocationURI(HttpResponse response, HttpContext context)
throws ProtocolException
{
Log.d(TAG, "getLocationURI, response: " + response.toString());
return null;
}
});
HttpResponse resp = null;
StringBuilder out = new StringBuilder();
try
{
HttpGet get = new HttpGet(spec);
resp = htc.execute(get);
for (Header hdr : resp.getAllHeaders())
Log.d(TAG, "header " + hdr.getName() + " -> " + hdr.getValue());
...
}
catch (Exception e)
{
Log.e(TAG, "Error connecting to " + spec, e);
return null;
}
Search for a substring in the HttpPost url
I'm building my first android app - something that will display my tweets in a list.
I managed to get the app working earlier, but the tweets would sometimes take a long time to download, and the app would become unresponsive or crash.
I decided to add a thread to the app so the it wouldn't become unresponsive, but now it doesn't work at all :/
Does anyone know what's wrong? It's only my third day of learning java, and I can't seem to figure out what the problem is here.
Here's the code:
package com.app.first;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
public class Twitter extends ListActivity {
public ProgressDialog pd = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// Show the ProgressDialog on this thread
pd = ProgressDialog.show(this, "Working..", "Downloading Data...",
true, false);
new LoadTwitterFeed().execute();
}
public class LoadTwitterFeed extends AsyncTask<String, Integer, String> {
String tweets[] = new String[9];
public String readTwitterFeed() {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(
"https://api.twitter.com/1/statuses/user_timeline.json?screen_name=jjmpsp&include_rts=false&count=10");
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e(ParseJSON.class.toString(), "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String readTwitterFeed = readTwitterFeed();
try {
JSONArray jsonArray = new JSONArray(readTwitterFeed);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
tweets[i] = jsonObject.getString("text").toString();
}
} catch (Exception e) {
e.printStackTrace();
}
setListAdapter(new ArrayAdapter<String>(Twitter.this,
android.R.layout.simple_list_item_1, tweets));
return null;
}
#Override
protected void onPostExecute(String result) {
// what to do when the task ends.
pd.hide();
}
}
}
set this code in onPostExecute
setListAdapter(new ArrayAdapter<String>(Twitter.this,
android.R.layout.simple_list_item_1, tweets));