First of all i would like to say that im very new to developing android and right now im just following a tutorial on how to develop an application that also uses login.
i have already finished to check if the user exist and the app will display a status saying if the login is a success.
now i would like to check if the user has an administrator role or a user role which is saved in the database.
tqvm in advanced.
below is the coding
1. MainActivity.java
package com.example.user.mysqldemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
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);
}
}
2.BackgroundWorker.java
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://ipaddress/foldername/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,"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();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
You login.php script must return the value of the login status and also the role of the person in the response.
A JSON structure like this,
{
"status" = 1, //0 or 1 depending on login result
"role" = 1 //a number based on the user type
}
Then you can parse this JSON result in onPostExecute and display the results.
#Override
protected void onPostExecute(String result) {
JSONObject jso = new JSONObject(result);
int status = jso.getInt("status")
int role = jso.getInt("role")
if(status == 1){
alertDialog.setMessage(result);
alertDialog.show();
if(role == 0){
//User
} else if(role == 1){
//Admin
}
} else{
//Login Failed
}
}
Related
I want to show Progress Dialog when background task is executed by doInbackground Method of AsyncTask Class, But the problem is when my server is off (Wamp server turns off) it doesnot shows Progress Dialog when trying to get connected with the server.
Please Help in this regard.
Main Class:
import android.app.AlertDialog;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity{
Button btnSubmitOrder;
EditText edDealerID;
EditText edProductID;
EditText edQuantity;
String stDealerID;
String stProductID;
String stQuantity;
String stUnit;
String stDate;
String stTime;
String stStatus;
ProgressBar edProgress;
Date currentDate = Calendar.getInstance().getTime();
DatabaseSQLite objDatabaseSqlite;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Date objDate = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("dd/MMM/yyyy");
stDate = df.format(objDate);
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
stTime = sdf.format(objDate);
final Spinner dropdown = findViewById(R.id.edit_unit);
String[] items = new String[]{"Box", "Packets"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, items);
dropdown.setAdapter(adapter);
objDatabaseSqlite = new DatabaseSQLite(this);
btnSubmitOrder = findViewById(R.id.btn_submitorder);
edDealerID = findViewById(R.id.edit_dealerid);
edProductID = findViewById(R.id.edit_productid);
edQuantity = findViewById(R.id.edit_quantity);
edProgress = findViewById(R.id.ed_progress);
btnSubmitOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stDealerID = edDealerID.getText().toString();
stProductID = edProductID.getText().toString();
stQuantity = edQuantity.getText().toString();
stUnit = dropdown.getSelectedItem().toString();
stStatus = "Pending";
BackgroundTask objBackground = new BackgroundTask(MainActivity.this);
try {
String response = objBackground.execute(stDealerID, stProductID, stQuantity, stUnit, stDate, stTime, stStatus).get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
BackgroundTask Class:
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
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 Saffi on 3/17/2016.
*/
public class BackgroundTask extends AsyncTask<String,Void,String> {
private String response = "";
private ProgressDialog dialog;
Context ctx;
BackgroundTask(Context ctx)
{
this.ctx = ctx;
}
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(ctx);
dialog.setMessage("Progress start");
dialog.show();
}
protected String doInBackground(String... params) {
String sendInvoice = "http://10.0.2.2/YounasTraders/SendInvoice.php";
String dealerId = params[0];
String productId = params[1];
String quantity = params[2];
String unit = params[3];
String date = params[4];
String time = params[5];
String status = params[6];
try {
URL objurl = new URL(sendInvoice);
HttpURLConnection objhttpurlconnection = (HttpURLConnection) objurl.openConnection();
objhttpurlconnection.setRequestMethod("POST");
objhttpurlconnection.setDoOutput(true);
objhttpurlconnection.setDoInput(true);
OutputStream objos = objhttpurlconnection.getOutputStream();
BufferedWriter objbuffwrite = new BufferedWriter(new OutputStreamWriter(objos, "UTF-8"));
String data = URLEncoder.encode("dealer_id", "UTF-8") +"="+URLEncoder.encode(dealerId, "UTF-8")+"&"+
URLEncoder.encode("product_id", "UTF-8")+"="+URLEncoder.encode(productId, "UTF-8")+"&"+
URLEncoder.encode("quantity", "UTF-8")+"="+URLEncoder.encode(quantity, "UTF-8")+"&"+
URLEncoder.encode("unit", "UTF-8")+"="+URLEncoder.encode(unit, "UTF-8")+"&"+
URLEncoder.encode("date", "UTF-8")+"="+URLEncoder.encode(date, "UTF-8")+"&"+
URLEncoder.encode("time", "UTF-8")+"="+URLEncoder.encode(time, "UTF-8")+"&"+
URLEncoder.encode("status", "UTF-8")+"="+URLEncoder.encode(status, "UTF-8");
objbuffwrite.write(data);
objbuffwrite.flush();
objbuffwrite.close();
objos.close();
InputStream objis = objhttpurlconnection.getInputStream();
objis.close();
objhttpurlconnection.disconnect();
response = "Order Sent Successfully";
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
response = "Order Not Sent Successfully";
return response;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
dialog.show();
}
#Override
protected void onPostExecute(String value) {
dialog.dismiss();
}
}
The problem is you are executing a task on main thread using .get method
The first change your AsyncTask task include this callback interface to call it after finishing your HTTP request
public class BackgroundTask extends AsyncTask {
private CallBack callBack;
public CallBack getCallBack() {
return callBack;
}
public void setCallBack(CallBack callBack) {
this.callBack = callBack;
}
private String response = "";
private ProgressDialog dialog;
Context ctx;
BackgroundTask(Context ctx)
{
this.ctx = ctx;
}
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(ctx);
dialog.setMessage("Progress start");
dialog.show();
}
protected String doInBackground(String... params) {
String sendInvoice = "http://10.0.2.2/YounasTraders/SendInvoice.php";
String dealerId = params[0];
String productId = params[1];
String quantity = params[2];
String unit = params[3];
String date = params[4];
String time = params[5];
String status = params[6];
try {
URL objurl = new URL(sendInvoice);
HttpURLConnection objhttpurlconnection = (HttpURLConnection) objurl.openConnection();
objhttpurlconnection.setRequestMethod("POST");
objhttpurlconnection.setDoOutput(true);
objhttpurlconnection.setDoInput(true);
OutputStream objos = objhttpurlconnection.getOutputStream();
BufferedWriter objbuffwrite = new BufferedWriter(new OutputStreamWriter(objos, "UTF-8"));
String data = URLEncoder.encode("dealer_id", "UTF-8") +"="+URLEncoder.encode(dealerId, "UTF-8")+"&"+
URLEncoder.encode("product_id", "UTF-8")+"="+URLEncoder.encode(productId, "UTF-8")+"&"+
URLEncoder.encode("quantity", "UTF-8")+"="+URLEncoder.encode(quantity, "UTF-8")+"&"+
URLEncoder.encode("unit", "UTF-8")+"="+URLEncoder.encode(unit, "UTF-8")+"&"+
URLEncoder.encode("date", "UTF-8")+"="+URLEncoder.encode(date, "UTF-8")+"&"+
URLEncoder.encode("time", "UTF-8")+"="+URLEncoder.encode(time, "UTF-8")+"&"+
URLEncoder.encode("status", "UTF-8")+"="+URLEncoder.encode(status, "UTF-8");
objbuffwrite.write(data);
objbuffwrite.flush();
objbuffwrite.close();
objos.close();
InputStream objis = objhttpurlconnection.getInputStream();
objis.close();
objhttpurlconnection.disconnect();
response = "Order Sent Successfully";
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
response = "Order Not Sent Successfully";
return response;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
dialog.show();
}
#Override
protected void onPostExecute(String value) {
dialog.dismiss();
if(callBack != null)
callBack.onResult(value);
}
public interface CallBack{
void onResult(String value);
}
}
Second change execution of your async task, get result on callback
BackgroundTask objBackground = new BackgroundTask(MainActivity.this);
objBackground.setCallBack(new BackgroundTask.CallBack() {
#Override
public void onResult(String value) {
//get here your response
}
});
objBackground.execute(stDealerID, stProductID, stQuantity, stUnit, stDate, stTime, stStatus);
MainActivivity.java
package com.example.anubhav.notesapp;
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 android.widget.Toast;
public class MainActivity2 extends AppCompatActivity {
String url;
EditText et;
TextView t1;
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
et = (EditText)findViewById(R.id.editText2);
t1 = (TextView)findViewById(R.id.textView3);
btn = (Button)findViewById(R.id.button);
url = dictionaryEntries();
}
public void requestApiButtonClick(View v)
{
MyDictionaryRequest myDictionaryRequest = new MyDictionaryRequest(this,t1);
myDictionaryRequest.execute(url);
}
private String dictionaryEntries() {
final String language = "en";
final String word = et.getText().toString();
final String word_id = word.toLowerCase();
return "https://od-api.oxforddictionaries.com:443/api/v1/entries/" + language + "/" + word_id;
}
}
DictionaryRequest.java
public class MyDictionaryRequest extends AsyncTask<String,Integer,String> {
final String app_id = "your_apiId";
final String app_key = "Your api_key";
String myurl;
TextView t1;
Context context;
Handler h = new Handler();
MyDictionaryRequest(Context context,TextView t1){
this.context = context;
this.t1=t1;
}
#Override
protected String doInBackground(String... strings) {
myurl = strings[0];
try {
URL url = new URL(myurl);
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setRequestProperty("Accept","application/json");
urlConnection.setRequestProperty("app_id",app_id);
urlConnection.setRequestProperty("app_key",app_key);
// read the output from the server
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
return stringBuilder.toString();
}
catch (Exception e) {
e.printStackTrace();
return e.toString();
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
String def;
try{
JSONObject js = new JSONObject(s);
JSONArray results = js.getJSONArray("results");
JSONObject lentries = results.getJSONObject(0);
JSONArray lArray= lentries.getJSONArray("lexicalEntries");
JSONObject entries = lArray.getJSONObject(0);
JSONArray e = entries.getJSONArray("entries");
JSONObject senses = e.getJSONObject(0);
JSONArray sensesArray = senses.getJSONArray("senses");
JSONObject d = sensesArray.getJSONObject(0);
JSONArray de = d.getJSONArray("definitions");
def=de.getString(0);
t1.setText(def);
Toast.makeText(context,def,Toast.LENGTH_SHORT).show();
}catch (Exception e)
{
e.printStackTrace();
}
}
}
Everthing is working fine in this code except that I can't get the word's meaning through edit text.
To be more specific :
The code works fine when I add
final String word = "car";
in dictionaryEntries() under Mainactivity.java
but nothing is displayed when :
final String word = et.getText().toString();
you have to move one of your code :
public void requestApiButtonClick(View v) {
MyDictionaryRequest myDictionaryRequest = new MyDictionaryRequest(this, t1);
url = dictionaryEntries();
myDictionaryRequest.execute(url);
}
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.
Aim: Building app on Google API to fetch the data about the books the user searches
Problem Explanation:
Whenever I hit the submit Button, my app crashes.
This is my first approach in making a network request app and I need guidance.
MainActivityClass
package com.example.vidit.books;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText query = (EditText) findViewById(R.id.query);
Button submit= (Button) findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent= new Intent(MainActivity.this,Request.class);
intent.putExtra ( "text", query.getText().toString() );
startActivity(intent);
}
});
}
}
Second Class
package com.example.vidit.books;
import android.content.Intent;
public class Request {
Intent i = getIntent();
String text = i.getStringExtra ("text");
public static final String LOG_TAG = Request.class.getSimpleName();
String APIURL="https://www.googleapis.com/books/v1/volumes?q= " + text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_request);
}
public void UpdateUi(Book book)
{
BookAdapter bookAdapter = new BookAdapter(this,book);
ListView listView= (ListView) findViewById(R.id.listview_all);
}
private class BookAsyncTask extends AsyncTask<URL,Void,Book>
{
#Override
protected Book doInBackground(URL... urls) {
URL url = createUrl(APIURL);
String jsonResponse = "";
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
// TODO Handle the IOException
}
final Book book = extractFeatureFromJson(jsonResponse);
return book;
}
/**
* Make an HTTP request to the given URL and return a String as the response.
*/
private String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.connect();
if(urlConnection.getResponseCode()==200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
}
} catch (IOException e) {
// TODO: Handle the exception
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
// function must handle java.io.IOException here
inputStream.close();
}
}
return jsonResponse;
}
/**
* Convert the {#link InputStream} into a String which contains the
* whole JSON response from the server.
*/
private String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
/**
* Returns new URL object from the given string URL.
*/
private URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException exception) {
Log.e(LOG_TAG, "Error with creating URL", exception);
return null;
}
return url;
}
private Book extractFeatureFromJson(String bookJSON) {
try {
JSONObject baseJsonResponse = new JSONObject(bookJSON);
JSONArray items = baseJsonResponse.getJSONArray("items");
// If there are results in the features array
for(int i=0;i<10;i++)
{
JSONObject firstFeature = items.getJSONObject(i);
JSONArray author=firstFeature.getJSONArray("author");
for(int j=0;j<author.length();j++)
{
JSONObject authorFeature=author.getJSONObject(j);
}
String title = items.getString(Integer.parseInt("title"));
// Create a new {#link Event} object
return new Book(title,author);
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Problem parsing the earthquake JSON results", e);
}
return null;
}
}
}
BookAdapter Class:
package com.example.vidit.books;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
public class BookAdapter extends ArrayAdapter<Book> {
public BookAdapter(Activity context, Book book)
{
super(context,0, (List<Book>) book);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if(listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
Book cbook=getItem(position);
TextView title = (TextView) listItemView.findViewById(R.id.title);
title.setText(cbook.getmTitle());
TextView author=(TextView) listItemView.findViewById(R.id.author);
author.setText((CharSequence) cbook.getmAuthor());
return listItemView;
}
}
Showing error in statement:
String text = i.getStringExtra ("text");
Need guidance
I don't know how your code gets compiled when you have overridden onCreate() in Request class and the Request class isn't extending Activity or AppCompatActivity.
Secondly, this line :
Intent i = getIntent();
String text = i.getStringExtra ("text");
should be inside the onCreate() method.
Showing error in statement : String text = i.getStringExtra ("text");
Request for Guidance
Well you need to get the data passed inside onCreate like below.
String APIURL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_request);
Bundle bundle = getIntent().getExtras();
String text = bundle.getString("text");
APIURL="https://www.googleapis.com/books/v1/volumes?q= " + text;
}
And although you have the asyncTask class i can't see where exactly you execute the class. You need to do that inside onCreate as well.
Try moving this code to your onCreate method
Intent i = getIntent();
String text = i.getStringExtra ("text");
The intent extras is not available in the constructor for your Request class.
I am new for Android i want to know how to connect database.I saw one video in you tube and i follow hole video but its not working.i don't know where i made mistake. please help me.from one week an words i'm trying but now also i'm not getting solution please help me stack over flow.
class ServerRequests {
ProgressDialog progressDialog;
public static final int CONNECTION_TIMEOUT=1000*15;
public static final String
SERVER_ADDRESS="http://192.168.1.11/myfolder/new1.php";
public ServerRequests(Context context){
progressDialog=new ProgressDialog(context);
progressDialog.setCancelable(false);
progressDialog.setTitle("processing");
progressDialog.setMessage("please wait.....");
}
public void storeUserDataInBackground(User user,GetUserCallbackuserCallback{
progressDialog.show();
new StoreUserDataAsyncTask(user,userCallback).execute();
}
public void fetchUserDataInBackground(User user,GetUserCallback callBack){
progressDialog.show();
new fetchUserDataAsynctask(user,callBack).execute();
}
public class StoreUserDataAsyncTask extends AsyncTask<Void,Void,Void>{
User user;
GetUserCallback userCallback;
public StoreUserDataAsyncTask(User user,GetUserCallback userCallback){
this.user=user;
this.userCallback=userCallback;
}
#Override
protected Void doInBackground(Void... params) {
ArrayList<NameValuePair>dataToSend=new ArrayList<>();
dataToSend.add(new BasicNameValuePair("name",user.name));
dataToSend.add(new BasicNameValuePair("age",user.age + ""));
dataToSend.add(new BasicNameValuePair("username",user.username));
dataToSend.add(new BasicNameValuePair("password",user.password));
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams,CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams,CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(SERVER_ADDRESS + "Register.php");
try{
post.setEntity(new URLEncoderFormEntity(dataToSend));
client.execute(post);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onpostExecute(Void aVoid){
progressDialog.dismiss();
userCallback.done(null);
super.onPostExecute(aVoid);
}
}
public fetchUserDataAsyncTask extends AsyncTask<Void,Void,User>{
User user;
GetUserCallback userCallback;
public fetchUserDataAsyncTask(User user,GetUserCallback userCallback){
this.user=user;
this.userCallback = userCallback;
}
#Override
protected User doInBackground(Void... params){
ArrayList<NameValuePair>dataToSend=new ArrayList<>();
dataToSend.add(new BasicNameValuePair("username",user.username));
dataToSend.add(new BasicNameValuePair("password",user.password));
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(SERVER_ADDRESS + "FetchUserData.php");
User returnedUser=null;
try{
post.setEntity(new URLEncoderFormEntity(dataToSend));
HttpResponce httpResponce=client.execute(post);
HttpEntity entity=httpResponce.getEntity();
String result= EntityUtils.toString(entity);
JSONObject jObject=new JSONObject(result);
if (jObject.length()==0){
user=null;
}else{
String name=jObject.getString("name");
int age =jObject.getInt("age");
returnedUser=new User(name,age,user.username,user.password);
}
}catch (Exception e){
e.printStackTrace();
}
return returnedUser;
}
#Override
protected void onPostExecute(User returnedUser){
progressDialog.dismiss();
userCallback.done(null);
super.onPostExecute(returnedUser);
}
}
}
enter code here
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
Button blogin;
EditText etusername,etpassword;
TextView tvregister;
UserLocalStore userLocalStore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
etusername=(EditText)findViewById(R.id.username_edit);
etpassword=(EditText)findViewById(R.id.password_edit);
blogin=(Button)findViewById(R.id.login_button);
tvregister=(TextView)findViewById(R.id.tv_register);
blogin.setOnClickListener(this);
tvregister.setOnClickListener(this);
userLocalStore=new UserLocalStore(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.login_button:
String username=etusername.getText().toString();
String password=etpassword.getText().toString();
User user=new User(username,password);
authenticate(user);
userLocalStore.storeUserData(user);
userLocalStore.setUserLoggedIn(true);
break;
case R.id.tv_register:
startActivity(new Intent(this,RegisterActivity.class));
break;
}
}
private void authenticate(User user) {
ServerRequests serverRequests = new ServerRequests(this);
serverRequests.fetchUserDataInBackground(user, new GetUserCallback() {
#Override
public void done(User returnedUser) {
if (returnedUser == null) {
showErrorMessage();
}else {
logUserIn(returnedUser);
}
}
});
}
private void showErrorMessage() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(LoginActivity.this);
dialogBuilder.setMessage("Incorrect user details");
dialogBuilder.setPositiveButton("ok", null);
dialogBuilder.show();
}
private void logUserIn(User returnedUser){
userLocalStore.storeUserData(returnedUser);
userLocalStore.setUserLoggedIn(true);
startActivity(new Intent(this,MainActivity.class));
}
}
Here is the link which you can refer for fetching data from server.
For Creating Web Service using PHP Click here
<?php
include("connect.php");
$result="";
//get data from users (name for user variable is p1 and p2
//here I am stroing this value to par1 and par2
//method i am using is GET
$par1=$_GET['p1'];
$par2=$_GET['p2'];
$eve = "select * from table where field1='$par1' and field2='$par2'";
$re = mysql_query($eve);
$response = array();
$posts = array();
while($rt = mysql_fetch_array($re))
{
$f1=$rt['field1'];
$f2=$rt['field2'];
break;
}
$posts[] = array('p1'=> $f1,'p2'=> $f2);
$response['posts'] = $posts;
echo stripslashes(json_encode( array('item' => $posts)));
?>
For AsyncTask Example Click here
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Login extends AppCompatActivity {
boolean remember;
private ProgressDialog pDialog;
public static final String PREFS_NAME = "Preference";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
((Button) findViewById(R.id.btnlogin)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Login Validation
try {
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Verifying...");
pDialog.show();
LoginVerifyTask g = new LoginVerifyTask();
g.execute(((EditText) findViewById(R.id.mobile)).getText().toString(), ((EditText) findViewById(R.id.password)).getText().toString());
} catch (Exception e) {
Log.e("cs", "catch error");
}
}
});
((TextView) findViewById(R.id.newuserregistrationtxtview)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), Registration1.class);
startActivity(i);
}
});
}
public class LoginVerifyTask extends AsyncTask<String, Void, String>
{
String u,p;
void LoginActivity(String s)
{
}
#Override
protected void onPostExecute(String json) {
// TODO Auto-generated method stub
pDialog.dismiss();
pDialog = null;
if (json == null)
{
return;
}
String csv="";
try {
JSONObject js = new JSONObject(json);
JSONArray user = js.getJSONArray("item");
for(int i=0;i<user.length();i++)
{
JSONObject j2 = user.getJSONObject(i);
//received data
String result = j2.get("p1").toString();
break;
}
}
catch(JSONException js)
{
}
return;
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
u = params[0];
p = params[1];
String tempdata="";
String buffer="";
try
{
URL url = new URL("http://websitename.com/folder/webservice.php?p1=" + params[0].replace(" ", "%20") + "&p2=" + params[1].replace(" ", "%20"));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
InputStream is = conn.getInputStream();
//buffer = new String();
if(is==null)
{
return tempdata;
}
else
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line="";
while( (line = reader.readLine())!=null)
{
buffer += line;
}
return buffer;
}
}
catch(Exception e)
{
Log.e("cs", e.toString());
}
return buffer;
}
}
}