At the moment I can add users into the database through postman or emulator but I need to be able insert the data from actual android device .What adjustments do I have to take ? Please have a look at the code below
This is my main activity that I using in my app :
package ie.example.artur.adminapp;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.HashMap;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
EditText editTextName,editTextEmail,editTextPassword;
TextView textView;
private static final String DB_URL = "jdbc:mysql://10.3.2.51/socialmedia_website";
private static final String USER = "zzz";
private static final String PASS = "zzz";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
findViewById(R.id.layoutProgress).setVisibility(View.GONE);
textView = (TextView) findViewById(R.id.textView);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
public void btnConn(View view) {
findViewById(R.id.layoutProgress).setVisibility(View.VISIBLE);
final ApiClient apiClient = new ApiClient();
String email = editTextEmail.getText().toString();
String name = editTextName.getText().toString();
String password = editTextPassword.getText().toString();
HashMap<String,String> parameters = new HashMap<>();
parameters.put("email",email);
parameters.put("name",name);
parameters.put("password",password);
Call<ApiResponse> call = apiClient.loginUser(parameters);
call.enqueue(new Callback<ApiResponse>() {
#Override
public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
if(response.isSuccessful())
{
ApiResponse apiResponse = response.body();
if(apiResponse.getStatus() == 200 || apiResponse.getStatus() == 201)
{
findViewById(R.id.layoutProgress).setVisibility(View.GONE);
Send objSend = new Send();
objSend.execute("");
//Toast.makeText(MainActivity.this,"Success", Toast.LENGTH_SHORT);
textView.setText("Success.");
}
else
{
//Toast.makeText(MainActivity.this,apiResponse.getErrors(), Toast.LENGTH_SHORT);
textView.setText(apiResponse.getErrors());
}
}
else
{
findViewById(R.id.layoutProgress).setVisibility(View.GONE);
//Toast.makeText(MainActivity.this,"Invalid api response.", Toast.LENGTH_SHORT);
textView.setText("Invalid api response.");
}
}
#Override
public void onFailure(Call<ApiResponse> call, Throwable t) {
findViewById(R.id.layoutProgress).setVisibility(View.GONE);
//Toast.makeText(MainActivity.this,"No host available or please check network connectivity.", Toast.LENGTH_SHORT);
textView.setText("No host available or please check network connectivity.");
}
});
}
private class Send extends AsyncTask<String, String, String>
{
String msg = "";
String name = editTextName.getText().toString();
String email = editTextEmail.getText().toString();
String password = editTextPassword.getText().toString();
#Override
protected void onPreExecute() {
textView.setText("Please Wait Inserting Data");
}
#Override
protected String doInBackground(String... strings) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
if (conn == null) {
msg = "Connection goes wrong";
} else {
String query = "Insert INTO users (name,email,password) VALUES('" + name+"','"+email+"','"+password+"')";
Statement stmt = conn.createStatement();
stmt.executeUpdate(query);
msg = "Inserting Successful!!";
}
conn.close();
}
catch(
Exception e
)
{
msg = "Connection goes Wrong";
e.printStackTrace();
}
return msg;
}
#Override
protected void onPostExecute(String msg) {textView.setText(msg);}
}
}
Api client class
package ie.example.artur.adminapp;
import java.util.HashMap;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by asifj on 7/25/2017.
*/
public class ApiClient
{
private String BASE_URL = BuildConfig.BASE_URL;
ApiEndPoints apiService;
public ApiClient() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addInterceptor(logging); // <-- this is the important line!
Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).client(httpClient.build()).build();
apiService = retrofit.create(ApiEndPoints.class);
}
public Call<ApiResponse> loginUser(HashMap<String, String> parameters)
{
return apiService.usercreate(parameters);
}
}
If you need me to share any more class please let me know in the comments
//this is a class you'll call in you main activity
public class PostRequest extends AsyncTask<Void, Void, String> {
private String parameters;
private Context context;
public PostRequest(Context context) {
this.context = context;
Log.d("PostRequest", "Context set : " + context);
}
public void setParameters(String parameters) {
this.parameters = parameters;
Log.d("PostRequest", "Parameters set : " + parameters);
}
#Override
protected String doInBackground(Void... params) {
String response = null;
try {
URL url = new URL("url of your php script");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
OutputStreamWriter request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
response = sb.toString();
isr.close();
reader.close();
} catch (IOException e) {
// Error
}
return response;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
//in your main activity you'll call it like so
PostRequest postRequest = new PostRequest(getContext());
postRequest.setParameters("param1=" + "param1value" + "¶m2=" + "param2value");
postRequest.execute();
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);
I have a dialog fragment Java class which showing a dialog box it works so fine but the only problem is that the progressDialog is not showing while waiting for the response, this is different from the dialog box, this progressDialog works in AsyncTask while getting the response from the http.
here is my code:
package com.example.kapoyei.hatidtubigan.helper;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatDialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.kapoyei.hatidtubigan.R;
import com.example.kapoyei.hatidtubigan.other.Http;
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;
import static android.content.Context.CONNECTIVITY_SERVICE;
public class AddStation extends AppCompatDialogFragment implements View.OnClickListener {
public static String jsonObject; // THIS WILL BE THE HANDLER OF JSON LATER
Button btnCreate; // GET THE BUTTON
EditText etStationName, etAddress, etContact; // GET THE INPUT TEXT
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// CREATE A DIALOG BOX
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// GET THE LAYOUT
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.layout_addstation, null);
builder.setView(view);
builder.setCancelable(true);
// GET THE VALUES
etStationName = (EditText) view.findViewById(R.id.etStationName);
etAddress = (EditText) view.findViewById(R.id.etAddress);
etContact = (EditText) view.findViewById(R.id.etContact);
btnCreate = (Button) view.findViewById(R.id.btnCreate);
// SET CLICK LISTENER OF THE BUTTON
btnCreate.setOnClickListener(this);
return builder.create();
}
#Override
public void onClick(View view) {
if(view.getId() == R.id.btnCreate) {
if(etStationName.getText().toString().isEmpty() || etAddress.getText().toString().isEmpty() || etContact.getText().toString().isEmpty()) {
Toast.makeText(getActivity(), "All inputs are required!", Toast.LENGTH_LONG).show();
} else {
if(isNetworkAvailable()) {
Thread stationThread = new Thread() {
#Override
public void run() {
Looper.prepare();
String param = "n=" + etStationName.getText().toString() + "&a=" + etAddress.getText().toString() + "&c=" + etContact.getText().toString();
String endpoint = Http.url + "?type=addstation&" + param;
endpoint = endpoint.replace(" ", "%20");
new AddStation.StoreStation(getActivity()).execute(endpoint);
}
};
stationThread.start();
} else {
Toast.makeText(getActivity(), "Network unavailable", Toast.LENGTH_LONG).show();
}
}
}
}
public class StoreStation extends AsyncTask<String, Void, String> {
ProgressDialog pd;
private Context mContext;
public StoreStation(Context c) {
mContext = c;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(mContext);
pd.setMessage("Adding station ...");
pd.setCancelable(false);
pd.show();
}
#Override
protected void onPostExecute(String result) {
pd.cancel();
getResponse(result);
}
#Override
protected String doInBackground(String... url) {
String data = "";
jsonObject = "";
try {
String link = (String) url[0];
URL getURL = new URL(link);
HttpURLConnection huc = (HttpURLConnection) getURL.openConnection();
huc.setReadTimeout(10000);
huc.setConnectTimeout(15000);
huc.setRequestMethod("GET");
huc.setDoInput(true);
huc.connect();
InputStream is = huc.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
while((data = reader.readLine()) != null) {
jsonObject += data;
}
Log.i("", jsonObject);
return jsonObject;
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
private void getResponse(String json) {
if(json != null) {
try {
JSONObject jobj = new JSONObject(json);
JSONArray jarray = jobj.getJSONArray("station");
String result = "";
for(int i = 0; i < jarray.length(); i++) {
JSONObject obj = jarray.getJSONObject(i);
result = obj.getString("result");
}
if(result.equalsIgnoreCase("done")) {
Toast.makeText(mContext, "Successfully save!", Toast.LENGTH_LONG).show();
}
if(result.equalsIgnoreCase("exists")) {
Toast.makeText(mContext, "Station is already exists!", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(mContext, "Connection problem", Toast.LENGTH_LONG).show();
}
}
}
private boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return ni != null && ni.isConnected();
}
}
In Android, only Main thread /UI thread can update UI
Other thread cannot update UI but your code is trying to run asynch task(which is a thread which run off/on UI accordingly, awesome!) in a worker thread which is causing the issues.
Solution: Execute Asynch task on UI thread
public void onClick(View view) {
if(view.getId() == R.id.btnCreate) {
if(etStationName.getText().toString().isEmpty() || etAddress.getText().toString().isEmpty() || etContact.getText().toString().isEmpty()) {
Toast.makeText(getActivity(), "All inputs are required!", Toast.LENGTH_LONG).show();
} else {
if(isNetworkAvailable()) {
String param = "n=" + etStationName.getText().toString() + "&a=" + etAddress.getText().toString() + "&c=" + etContact.getText().toString();
String endpoint = Http.url + "?type=addstation&" + param;
endpoint = endpoint.replace(" ", "%20");
new AddStation.StoreStation(getActivity()).execute(endpoint);
} else {
Toast.makeText(getActivity(), "Network unavailable", Toast.LENGTH_LONG).show();
}
}
}
}
I've been sitting with this problem for 2 weeks now and I hope 1 of you can help me with this.
The following code I have for connecting with out database.
package com.example.sunapp;
import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionClass {
String ip = "xxx.xxx.xxx.xxx";
String classs = "net.sourgeforge.jtds.jdbc.Driver";
String db = "xxxx";
String un = "xxxx";
String password = "xxxx";
#SuppressLint("NewApi")
public Connection CONN() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn = null;
String ConnURL = null;
try {
Class.forName(classs);
ConnURL = "jdbc:jtds:sqlserver://" + ip + ";"
+ "databaseName=" + db + ";user=" + un + ";password="
+ password + ";";
conn = DriverManager.getConnection(ConnURL);
} catch (SQLException se) {
Log.e("ERRO1", se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("ERRO2", e.getMessage());
} catch (Exception e) {
Log.e("ERRO3", e.getMessage());
}
return conn;
}
}
When I hit 'Inloggen' I get the following error
"02-19 15:15:02.679 8488-10423/com.example.sunapp E/ERRO2: net.sourgeforge.jtds.jdbc.Driver"
Below the code of the login activity of the application
package com.example.sunapp;
import android.content.Intent;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.os.AsyncTask;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
public class LoginActivity extends AppCompatActivity {
//Declaring connection
ConnectionClass connectionClass;
EditText etGebruikersnaam, etWachtwoord;
CardView cvInloggen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ActionBar actionBar = getSupportActionBar();
assert actionBar != null;
actionBar.hide();
connectionClass = new ConnectionClass();
final EditText etGebruikersnaam = findViewById(R.id.etGebruikersnaam);
final EditText etWachtwoord = findViewById(R.id.etWachtwoord);
final CardView cvInloggen = findViewById(R.id.cvInloggen);
final TextView RegistreerLink = findViewById(R.id.tvRegistreren);
RegistreerLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent registreerIntent = new Intent(LoginActivity.this, RegistryActivity.class);
LoginActivity.this.startActivity(registreerIntent);
}
});
cvInloggen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DoLogin doLogin = new DoLogin();
doLogin.execute("");
}
});
}
public class DoLogin extends AsyncTask<String,String,String>
{
String z = "";
Boolean isSucces = false;
final EditText etGebruikersnaam = findViewById(R.id.etGebruikersnaam);
final EditText etWachtwoord = findViewById(R.id.etWachtwoord);
String userid = etGebruikersnaam.getText().toString();
String password = etWachtwoord.getText().toString();
#Override
protected String doInBackground(String... params) {
if(userid.trim().equals("")|| password.trim().equals(""))
z = "Vul hier uw gebruikersnaam en wachtwoord in";
else
{
try {
Connection con = connectionClass.CONN();
if (con == null) {
String query = "select * from compose.tblGebruikers where Gebruikersnaam='" + userid + "' and Wachtwoord='" + password + "'";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs.next())
{
z = "Login succesfull";
isSucces = true;
}
else
{
z = "Invalid Credentials";
isSucces = false;
}
}
}
catch (Exception ex)
{
isSucces = false;
z = "Exceptions";
}
}
return z;
}
}
}
I must be doing something wrong but, what is the question. the message I'm getting comes from the classnotfoundexception. I still not managed to make it work.
Main Activity :
package com.example.phpmysql;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private EditText usernameField,passwordField;
private TextView status,role,method;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usernameField = (EditText)findViewById(R.id.editText1);
passwordField = (EditText)findViewById(R.id.editText2);
status = (TextView)findViewById(R.id.textView6);
role = (TextView)findViewById(R.id.textView7);
method = (TextView)findViewById(R.id.textView9);
}
public void login(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Get Method");
new SigninActivity(this,status,role,0).execute(username,password);
}
public void loginPost(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Post Method");
new SigninActivity(this,status,role,1).execute(username,password);
}
}
SigninActivity:
package com.example.phpmysql;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.TextView;
public class SigninActivity extends AsyncTask{
private TextView statusField,roleField;
private Context context;
private int byGetOrPost = 0;
//flag 0 means get and 1 means post.(By default it is get.)
public SigninActivity(Context context,TextView statusField,TextView
roleField,int flag) {
this.context = context;
this.statusField = statusField;
this.roleField = roleField;
byGetOrPost = flag;
}
protected void onPreExecute(){
}
#Override
protected String doInBackground(String... arg0) {
if(byGetOrPost == 0){ //means by Get Method
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link = "http://myphpmysqlweb.hostei.com/login.php?username="+username+"& password="+password;
URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
} catch(Exception e){
return new String("Exception: " + e.getMessage());
}
} else{
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link="http://myphpmysqlweb.hostei.com/loginpost.php";
String data = URLEncoder.encode("username", "UTF-8") + "=" +
URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") + "=" +
URLEncoder.encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null) {
sb.append(line);
break;
}
return sb.toString();
} catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
}
#Override
protected void onPostExecute(String result){
this.statusField.setText("Login Successful");
this.roleField.setText(result);
}
}
The public class SigninActivity extends AsyncTask is shown in red underline saying Class SigninActivity must either be declared abstract or implement abstract method doInBackground(Params...) in AsyncTask?
I tried adding the doInBackground but it says that it is never used?
I tried making it adbstract but then i could not call the class from mainactivity
You need to provide the generic parameters as
public class SigninActivity extends AsyncTask<String, Void, String>
otherwise the parameter type will be of raw-type and signature won't match
I need some help on Instagram api in android development, i need to search feeds or tags of Instagram in my app, is any one have suggestion about on it? or please provide links of tutorial
Advance thanks
You can find all you need on the instagram developer page:
http://instagram.com/developer/endpoints/tags/
Instagram provides a RESTful API, so you will make simple HTTP-calls on URLs with your specified parameters (like a tag you want to search for). The response will be in JSON-format, from which you can extract the desired information such as image urls, user-name, etc.
With the bold parts above you have all you need reach your goal. Just google for these parts, here is a tutorial for implementing REST in Android. Also see this question on StackOverflow to reach a more advanced implementation: Android rest client sample.
Also Vogella's tutorial is great and shows you both parts, the request call and the response parsing.
Here is a function that creates the URl to search for a certain hashtag:
public static String getSearchUrl(String hashtag) {
return "https://api.instagram.com/v1/tags/" + hashtag
+ "/media/recent?client_id=" + Constants.CLIENT_ID;
}
package com.pgd.Fragments;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;
import com.pgd.Adepters.InstagramTimelineAdapter;
import com.pgd.Beans.InstagramBeans;
import com.pgd.R;
import com.pgd.SocialLogin.Params;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.GZIPInputStream;
/**
* Created by admin on 9/26/2017.
*/
public class InstagramTimelineFragment extends Fragment {
public static final String API_AUTH_URL = "https://instagram.com/oauth/authorize/?";
public static final String API_ACCESS_TOKEN_URL = "https://api.instagram.com/oauth/access_token";
public static final String API_BASE_URL = "https://api.instagram.com/v1";
public String CLIENT_ID = "8c1e17fd79e1402e915d94c1f05c5c3c";
public String CLIENT_SECRET = "8885809e2b934647bedcec7068ea3e78";
public String REDIRECT_URL = "https://stackoverflow.com/users/6286004/amit-bhatnagar";
String username = "";
String fullName = "";
String profilePicture = "";
String accessToken = "";
String id = "";
private WebView _webView;
private LinearLayout _loadProgressLayout;
private ProgressBar _loadProgressBar;
InstagramBeans instagramBeansList;
InstagramTimelineAdapter instagramTimelineAdapter;
private RecyclerView recyclerView;
public static final String InstagramTimelineFragment = "InstagramTimelineFragment";
public static InstagramTimelineFragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt(InstagramTimelineFragment, page);
InstagramTimelineFragment fragment = new InstagramTimelineFragment();
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.instagram_timeline_list, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.insta_recyclerView);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(mLayoutManager);
initWebView(view);
return view;
}
private void initWebView(View view) {
_loadProgressBar = (ProgressBar) view.findViewById(R.id.loadProgressBar);
_loadProgressLayout = (LinearLayout) view.findViewById(R.id.loadProgressLayout);
_webView = (WebView) view.findViewById(R.id.webView);
_webView.getSettings().setJavaScriptEnabled(true);
_webView.clearCache(true);
_webView.setWebViewClient(new InstagramWebViewClient());
_webView.setWebChromeClient(new InstagramWebChromeClient());
CookieSyncManager.createInstance(getActivity());
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
_webView.loadUrl(getCodeRequest(CLIENT_ID, REDIRECT_URL));
}
public String authorize(String clientId, String clientSecret, String redirectUrl, String code) throws IOException, JSONException {
Params params = new Params();
params.put("client_id", clientId);
params.put("client_secret", clientSecret);
params.put("redirect_uri", redirectUrl);
params.put("grant_type", "authorization_code");
params.put("code", code);
JSONObject rootJson = sendRequest(API_ACCESS_TOKEN_URL, params, Request.POST);
JSONObject userJson = rootJson.getJSONObject("user");
id = userJson.getString("id");
username = userJson.optString("username");
fullName = userJson.optString("full_name");
profilePicture = userJson.optString("profile_picture");
accessToken = rootJson.optString("access_token");
Log.d("name", username);
return accessToken;
}
public JSONObject sendRequest(String url, Params params, Request request) throws IOException, JSONException {
String signedUrl = getSignedUrl(url, params, request);
String body = "";
if (request == Request.POST)
body = params.getParamsStringUtf8();
System.out.println("Tag" + " url : " + signedUrl);
if (body.length() != 0)
System.out.println("Tag" + " body : " + body);
String response = "";
for (int i = 1; i <= 3; ++i) {
try {
if (i != 1)
System.out.println("tag" + " try send = " + i);
response = sendDummyRequest(signedUrl, body, request);
break;
} catch (Exception ex) {
ex.printStackTrace();
}
}
// JSONObject rootJSON = new JSONObject(response);
JSONObject rootJSON = (JSONObject) new JSONTokener(response).nextValue();
return rootJSON;
}
public enum Request {
GET,
POST
}
private String sendDummyRequest(String url, String body, Request request) throws IOException {
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) new URL(url).openConnection();
connection.setConnectTimeout(10000);
connection.setReadTimeout(10000);
connection.setUseCaches(false);
connection.setDoInput(true);
// connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
if (request == Request.GET) {
connection.setDoOutput(false);
connection.setRequestMethod("GET");
} else if (request == Request.POST) {
connection.setDoOutput(true);
connection.setRequestMethod("POST");
}
if (false)
connection.setRequestProperty("Accept-Encoding", "gzip");
if (request == Request.POST)
connection.getOutputStream().write(body.getBytes("utf-8"));
int code = connection.getResponseCode();
System.out.println("TAG" + " responseCode = " + code);
//It may happen due to keep-alive problem http://stackoverflow.com/questions/1440957/httpurlconnection-getresponsecode-returns-1-on-second-invocation
if (code == -1)
throw new IOException();
//может стоит проверить на код 200
//on error can also read error stream from connection.
InputStream inputStream = new BufferedInputStream(connection.getInputStream(), 8192);
String encoding = connection.getHeaderField("Content-Encoding");
if (encoding != null && encoding.equalsIgnoreCase("gzip"))
inputStream = new GZIPInputStream(inputStream);
String response = convertStreamToString(inputStream);
System.out.println("TAG" + " response = " + response);
return response;
} finally {
if (connection != null)
connection.disconnect();
}
}
private String getSignedUrl(String url, Params params, Request request) {
String signedUrl = url + params.getEndpoint();
if (request == Request.GET) {
String args = params.getParamsStringUtf8();
return signedUrl + "?" + args;
}
return signedUrl;
}
public String convertStreamToString(InputStream is) throws IOException {
InputStreamReader r = new InputStreamReader(is);
StringWriter sw = new StringWriter();
char[] buffer = new char[1024];
try {
for (int n; (n = r.read(buffer)) != -1; )
sw.write(buffer, 0, n);
} finally {
try {
is.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
return sw.toString();
}
public class InstagramWebViewClient extends WebViewClient {
#SuppressWarnings("deprecation")
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith(REDIRECT_URL)) {
final Intent intent = new Intent();
if (url.contains("code")) {
String temp[] = url.split("=");
final String code = temp[1];
new Thread(new Runnable() {
#Override
public void run() {
try {
accessToken = authorize(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL, code);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// getFeed();
// userNameTextView.setText(username);
//userFullnameTextView.setText(fullName);
//Picasso.with(getActivity()).load(profilePicture).into(userImageView);
_webView.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
getFeed();
}
});
} catch (final Exception e) {
e.printStackTrace();
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
intent.putExtra("error", e.getMessage());
// setResult(Activity.RESULT_OK, intent);
// finish();
}
});
}
}
}).start();
} else if (url.contains("error")) {
String temp[] = url.split("=");
String error = temp[temp.length - 1];
intent.putExtra("error", error);
// setResult(Activity.RESULT_OK, intent);
// finish();
}
return true;
}
return false;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
_loadProgressLayout.setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
_loadProgressLayout.setVisibility(View.GONE);
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
_loadProgressLayout.setVisibility(View.GONE);
Toast.makeText(getActivity(),
getString(R.string.page_load_error),
Toast.LENGTH_LONG).show();
Intent intent = new Intent();
intent.putExtra("error", description);
// setResult(Activity.RESULT_OK, intent);
//finish();
}
}
public String getCodeRequest(String clientId, String redirectUrl) {
return API_AUTH_URL + "client_id=" + clientId + "&redirect_uri=" + redirectUrl + "&response_type=code";
}
private class InstagramWebChromeClient extends WebChromeClient {
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
_loadProgressBar.setProgress(newProgress);
}
}
public void getFeed() {
try {
URL example = new URL("https://api.instagram.com/v1/users/self/media/recent?access_token="
+ accessToken);
Ion.with(getActivity())
.load(String.valueOf(example))
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception e, JsonObject result) {
// do stuff with the result or error
String response = result.toString();
Log.d("res_feed", response);
Gson gson = new Gson();
instagramBeansList = gson.fromJson(response, InstagramBeans.class);
if (instagramBeansList.getData().size() > 0) {
instagramTimelineAdapter = new InstagramTimelineAdapter(getActivity(), instagramBeansList.getData());
recyclerView.setAdapter(instagramTimelineAdapter);
} else {
Toast.makeText(getActivity(), "Data in empty", Toast.LENGTH_SHORT).show();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
} else {
}
}
}