QR Code to Google Sheets in Andriod Studio - android

I have many QR codes ex. Example on imgur, which has peoples' names, numbers, and emails, and I need to scan them. The data comes in something like this: "joe,1234567890,joe#joe.com". I want to write an app that uploads the data to a google sheet and I found a tutorial online from crazycodersclub.com, but when I do the same thing it gives me an error, something like:
Exception: Invalid argument: URL (line 11, file "Code")
Google Script Code
function doGet(e){
var url = encodeUrl("https://docs.google.com/spreadsheets/d/1IEAHcv2n33YO9d7IbfWNVLv2Hl1Q1UXveazPcgMZrMs/edit?usp=sharing/")
var ss = SpreadsheetApp.openByUrl(url);
var sheet = ss.getSheetByName("Sheet1");
return insert(e,sheet);
}
function doPost(e){
var url = encodeUrl("https://docs.google.com/spreadsheets/d/1IEAHcv2n33YO9d7IbfWNVLv2Hl1Q1UXveazPcgMZrMs/edit?usp=sharing/")
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1IEAHcv2n33YO9d7IbfWNVLv2Hl1Q1UXveazPcgMZrMs/edit?usp=sharing/");
var sheet = ss.getSheetByName("Sheet1");
return insert(e,sheet);
}
function insert(e,sheet) {
var scannedData = e.parameter.sdata;
var d = new Date();
var ctime = d.toLocaleString();
sheet.appendRow([scannedData,ctime]);
return ContentService
.createTextOutput("Success")
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
MainActivity.java
package com.tarbiya.scannerapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity {
String scannedData;
Button scanBtn;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Activity activity =this;
scanBtn = (Button)findViewById(R.id.scan_btn);
scanBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
IntentIntegrator integrator = new IntentIntegrator(activity);
integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
integrator.setPrompt("Scan");
integrator.setBeepEnabled(false);
integrator.setCameraId(0);
integrator.setBarcodeImageEnabled(false);
integrator.initiateScan();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode,resultCode,data);
if(result!=null) {
scannedData = result.getContents();
if (scannedData != null) {
// Here we need to handle scanned data...
new SendRequest().execute();
}else {
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public class SendRequest extends AsyncTask<String, Void, String> {
protected void onPreExecute(){}
protected String doInBackground(String... arg0) {
try{
//Enter script URL Here
URL url = new URL("https://script.google.com/macros/s/AKfycby_G_K-kmm77peQBSY6xmNZjsDcFIkDgqZwxz6e7guyte5Lxe8/exec");
JSONObject postDataParams = new JSONObject();
//int i;
//for(i=1;i<=70;i++)
// String usn = Integer.toString(i);
//Passing scanned code as parameter
postDataParams.put("sdata",scannedData);
Log.e("params",postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line="";
while((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}
else {
return new String("false : "+responseCode);
}
}
catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_LONG).show();
}
}
public String getPostDataString(JSONObject params) throws Exception {
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while(itr.hasNext()){
String key= itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}
}
If you need to see more code, I can attach some more. It looks basically the same as the one in the tutorial right now.
Thank you so much for your help.

The reason you were receiving the Exception: Invalid argument: URL message is because the url you were passing to the openByUrl was not in the correct format.
If you check the documentation for the openByUrl method here, you can see the accepted format of the link.
https://docs.google.com/spreadsheets/d/abc1234567/edit
In your situation, you will have to remove the part after the /edit.
Reference
Apps Script SpreadsheetApp Class - openByUrl(url).

Related

Android studio problems login validation

So I've been cracking my brain with this issues. I'm trying to validate if the an user credentials on a app connected to mysql are valid. The thing is that wherever I try to compare the result of the query with a string all I get is the else statement.
Here's the Fragment for the Login
package com.example.pablorjd.CheckThisOut;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Login extends AppCompatActivity {
EditText etUsername;
EditText etPassword;
Button btnLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
etUsername = (EditText)findViewById(R.id.etUsername);
etPassword = (EditText)findViewById(R.id.etPassword);
btnLogin = (Button)findViewById(R.id.btnLogin);
}
public void onLogin(View view){
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
String type = "login";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type,username,password);
}
}
I'm using a background class to make the connection to mysql
package com.example.pablorjd.CheckThisOut;
import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
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;
public class BackgroundWorker extends AsyncTask<String, Void, String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker(Context ctx){
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://10.20.13.31/checkthisout/login.php";
if (type.equals("login")){
try {
String user_name = params[1];
String password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("user_name", "UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8")+"&"
+URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String result = "";
String line = "";
while ((line = bufferedReader.readLine())!=null){
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(String result) {
if (result.equals("true")){
Toast.makeText(context, "If is working", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context,result, Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
I know the DB connections is working because I'm actually receiving the message that I set on the php file.
All I know is that for some reason the if statement is not working for this.
please if someone could shed a light for me that'd be great.
OK so, for some reason, the validation just wouldn't take the string comparison and instead jumped to the else statement showing in this case a Toast. What I had to do was to modify the string given to me by the php file so it would be just a number (0 or 1 in this case). then I parsed the string into an int and the if worked like a charm.
This is the resulting code
#Override
protected void onPostExecute(String result) {
int val = Integer.parseInt(result.replaceAll("[\\D]",""));
if (val == 0){
Intent intent = new Intent(context,MainActivity.class);
context.startActivity(intent);
Toast.makeText(context,"Login exitoso",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context,"Login erroneo",Toast.LENGTH_SHORT).show();
}
}
I still don't know why the if statement wouldn't work with strings.

POST request from android to Nodejs

im working on this program ,which i have an Android app that uses Nodejs server.the host is -https://rocky-thicket-82184.herokuapp.com.
now, im trying to just send and recieve a post request . but it seems to not
work.
in the server side i get an error like : cannot GET/.
and in the client side i get :error exeption https://rocky-thicket-82184.herokuapp.com.
I cannot find the problem ,i feel like i'm missing something ...
here is my Android mainActivity.java:
package com.example.shanijoffe.hungry_monkey;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.JsonReader;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.os.AsyncTask;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.stormpath.sdk.Stormpath;
import com.stormpath.sdk.StormpathConfiguration;
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.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.NameValuePair;
import cz.msebera.android.httpclient.client.ClientProtocolException;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.client.entity.UrlEncodedFormEntity;
import cz.msebera.android.httpclient.client.methods.HttpPost;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;
import cz.msebera.android.httpclient.message.BasicNameValuePair;
import static com.loopj.android.http.AsyncHttpClient.log;
public class MainActivity extends AppCompatActivity
{
EditText user_name_edit;
EditText password_edit;
Button loginButton;
String user;
String user_pass;
private static final String TAG = "MyActivity";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
user_name_edit=(EditText)findViewById(R.id.txt_usrname);
password_edit=(EditText)findViewById(R.id.txt_password);
loginButton=(Button)findViewById(R.id.btn_login);
Log.i(TAG,"before connection");
}
public void OnClick(final View view) {
view.setEnabled(false);
user=user_name_edit.getText().toString();
user_pass=password_edit.getText().toString();
new SendPostRequest().execute();
//
//
}
public class SendPostRequest extends AsyncTask<String, Void, String>
{
String user_name=user_name_edit.getText().toString();
String user_pass=password_edit.getText().toString();
protected void onPreExecute(){}
protected String doInBackground(String... arg0) {
try {
Log.e("MainActivity", "in SendPostRequest ");
URL url = new URL("https://rocky-thicket-82184.herokuapp.com");
InputStream inp = (InputStream) url.getContent();
Log.e("stream",inp.toString());
JSONObject postDataParams = new JSONObject();
postDataParams.put("username", user);
postDataParams.put("password", user_pass);
Log.e("params", postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
int responseCode;
try (BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"))) {
String encoded_string = getPostDataString(postDataParams);
Log.e("encoded", encoded_string);
//writer.write(getPostDataString(postDataParams));
writer.write(postDataParams.toString());
writer.flush();
writer.close();
}
os.close();
responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
Log.i("MainActivty",sb.toString());
return sb.toString();
} else {
return new String("false : " + responseCode);
}
}
catch (Exception e)
{
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_LONG).show();
}
public String getPostDataString(JSONObject params) throws Exception
{
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while(itr.hasNext()){
String key= itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}
}
}
and here is the nodejs code:
var express=require('express');
var bodyParser=require('body-parser');
var app=express();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.get('/',function(req,res){
res.sendFile(__dirname + '/index.html');
});
app.post('/',function(req,res){
console.log(req.body);
if (!req.body)
return res.sendStatus(400)
res.send('welcome, ' + req.body.user)
});
app.listen(process.env.PORT || 3000)
can anyone take a look and see if they can help ?
Thanks alot :)

consuming rest web service in android

I'am following this tutorial for calling a web service in android & it works great, http://androidexample.com/Restful_Webservice_Call_And_Get_And_Parse_JSON_Data-_Android_Example/index.php?view=article_discription&aid=101
yet when i try to call another webservice using this code, just replacing the serverURL, the app gets blocked in th pre-execute(), can anyone tell me what else should I change ? I thought there was a common code for all web services ?
mainActivity.java
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button GetData = (Button) findViewById(R.id.GetServerData);
GetData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// WebServer Request URL
String serverURL = "http://androidexample.com/media/webservice/JsonReturn.php";
// String serverURL = "http://hmkcode.appspot.com/rest/controller/get.json";
// String serverURL="http://gdata.youtube.com/feeds/api/videos?q=Android&v=2&max-results=20&alt=jsonc&hl=en";
// Use AsyncTask execute Method To Prevent ANR Problem
new LongOperation().execute(serverURL);
}
}
);
}
class LongOperation extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
String data = "";
TextView uiUpdate = (TextView) findViewById(R.id.output);
TextView jsonParsed = (TextView) findViewById(R.id.jsonParsed);
protected void onPreExecute() {
// NOTE: You can call UI Element here.
//Start Progress Dialog (Message)
Dialog.setMessage("Please wait..");
Dialog.show();
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server *********/
BufferedReader reader=null;
// Send data
try
{
// Defined URL where to send data
URL url = new URL(urls[0]);
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + " ");
}
// Append Server Response To Content String
Content = sb.toString();
}
catch(Exception ex)
{
Error = ex.getMessage();
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
/*****************************************************/
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
Dialog.dismiss();
if (Error != null) {
uiUpdate.setText("Output : " + Error);
} else {
// Show Response Json On Screen (activity)
uiUpdate.setText(Content);
//String OutputData = MainActivity.parse(Content);
//Show Parsed Output on screen (activity)
//jsonParsed.setText(OutputData);
}
}
}
}
I changed send PostRequest with this code: //SEND Get data reques HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET");& it works

Android dialog box with PIN input

I'm trying to do a PIN input as a dialog.
This part is working fine. But when I enter my pin and try to compare it to my requested pin it just closes my dialog.
So here is my code:
PinInput.java
package com.ts.techassi.ts;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class PinInput extends DialogFragment {
public final static String EXTRA_MESSAGE = "tuerschild.saschalautenschlaege.tuerschild.MESSAGE";
Context context;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.pin_input, null));
Log.i("LOL", "Started");
builder.setMessage("Enter PIN")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Uri url = readUrl();
Dialog f = (Dialog) dialog;
// String ts_id = url.getLastPathSegment();
EditText pin = (EditText)f.findViewById(R.id.pin);
TextView test = (TextView) f.findViewById(R.id.response);
String pinString = pin.getText().toString();
try {
String response = new Http().execute().get();
// Log.i("test", response);
if( response == pinString) {
Boolean isLauncher = isMyAppLauncherDefault();
if(isLauncher == true){
resetPreferredLauncherAndOpenChooser(context);
}
} else {
PinInput.this.getDialog().cancel();
}
} catch (Exception e) {
e.printStackTrace();
Log.i("Test",e.toString());
}
}
})
.setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
return builder.create();
}
public Uri readUrl() {
String fileDirectory = Environment.getExternalStorageDirectory()+"/dbDoorsign/url.txt";
File file = new File(fileDirectory);
StringBuilder text = new StringBuilder();
;
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
}
br.close();
}
catch (IOException e) {
}
return Uri.parse(text.toString());
}
private boolean isMyAppLauncherDefault() {
final IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
filter.addCategory(Intent.CATEGORY_HOME);
List<IntentFilter> filters = new ArrayList<IntentFilter>();
filters.add(filter);
final String myPackageName = getActivity().getPackageName();
List<ComponentName> activities = new ArrayList<ComponentName>();
final PackageManager packageManager = (PackageManager) getActivity().getPackageManager();
packageManager.getPreferredActivities(filters, activities, null);
for (ComponentName activity : activities) {
if (myPackageName.equals(activity.getPackageName())) {
return true;
}
}
return false;
}
public static void resetPreferredLauncherAndOpenChooser(Context context) {
PackageManager packageManager = context.getPackageManager();
ComponentName componentName = new ComponentName(context, FakeLauncherActivity.class);
packageManager.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
Intent selector = new Intent(Intent.ACTION_MAIN);
selector.addCategory(Intent.CATEGORY_HOME);
selector.putExtra(EXTRA_MESSAGE, "1");
selector.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(selector);
packageManager.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, PackageManager.DONT_KILL_APP);
}
}
My second file Http.java
package com.ts.techassi.ts;
import android.os.AsyncTask;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Http extends AsyncTask<String, Void, String> {
String USER_AGENT = "Mozilla/5.0";
private TextView scanResults;
#Override
protected String doInBackground(String... url) {
try {
return sendGet();
} catch (Exception e) {
e.printStackTrace();
return e.toString();
}
}
private String sendGet() throws Exception {
String url = "http://my.url.com";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
// System.out.println(response.toString());
return response.toString();
}
}
EDIT 1:
Changed if( pinString == response) to if( pinString.equals(response))
So I thinks thats all you need. I hope you can help me.
The problem is this line:
if( response == pinString) {
Never compare Strings like this in Java. Change it to:
if( pinString.equals(response) ) {
The reason is that, in Java, == operator compares instances, not contents. It works for primitives (like ints and longs), but Objects, including Strings, need to be compared with the .equals() method, which compares the contents, not the instance.

Intent in android error

Everyone i'm getting error while using Intent in android. I have a MainActivity from where i call another class called BackgroundWorker so after doing some functions of login i want to go to user page if it is a sucesss.enter code here im attaching my code here Please help
package com.example.user.mybookapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText UsernameEt, PasswordEt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
UsernameEt = (EditText) findViewById(R.id.etusername);
PasswordEt = (EditText) findViewById(R.id.etpassword);
}
public void OnLogin(View view) {
String username = UsernameEt.getText().toString();
String password = PasswordEt.getText().toString();
String type = "login";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type,username,password);
}
}
//BackgoundWorker class
package com.example.user.mybookapp;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.widget.Toast;
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;
/**
* Created by user on 15-09-2016.
*/
public class BackgroundWorker extends AsyncTask<String,Void,String> {
public Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx){
context = ctx;
}
#Override
protected String doInBackground(String[] params)
{
String type = params[0];
String login_url = "http://192.168.4.2/login.php";
if(type.equals("login"))
{
try {
//Context context = getApplicationContext();
//Toast t= Toast.makeText(ctx,"click",Toast.LENGTH_SHORT).show();
//alertDialog = new AlertDialog.Builder(context).create();
//alertDialog.setTitle("login status");
String user_name = params[1];
String password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8")+"&"
+URLEncoder.encode(password,"UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine())!=null){
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("login status");
}
#Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
alertDialog.show();
String s=result.trim();
if (s.equalsIgnoreCase("success")){
Intent i =Intent(BackgroundWorker.this,User.class);//Problem
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
Intent i =Intent(context,User.class);
This should fix the error, intent should be called using current context.
Intent i =Intent(context,User.class);
context.startActivity(i);
This will work as BackgroundWorker.this is a non activity reference.
Intent intent = new Intent(mContext,SecondClass.class);
intent.putExtra("KEY","Value");
startActivity(intent);
//here KEY = the identifier of specific value
//on other side of SecondClass Activity. catch this data using
String res = getIntent().getStringExtra("KEY");
Intent constructor needs a context as first parameter and you are giving it AsyncTask. You are not constructing object of Intent class properly, in other words you have forgotten to write new keyword.This is the syntax to create a object:-
<Class> <objectName> = new <Class/Subclass>(constructor_params_separated_by_commas);
Intent i =Intent(BackgroundWorker.this,User.class);//Problem
change it to
Intent i =new Intent(context,User.class);//Problem solved
context.startActivity(i);
As mentioned in the answers above, first problem is the inappropriate context, second problem is that you are passing wrong arguments in your background worker class while performing background task execution. Your AsyncTask extension:
AsyncTask<String, Void, String>
shows that you must pass String in doInBackground method, while in the code above you are trying to get string Array although you have passed String parameters from your main activity i.e
protected String doInBackground(String[] params)
should be
protected String doInBackground(String... params)
Hope that solves the issue.

Categories

Resources