I made a very simple app just to stabilished a connection with my SQL database on Raspberry Pi with JDBC but when I tried to connect, the app give me a error, any suggest?
code:
public class MainActivity extends AppCompatActivity {
private static final String url = "jdbc:mysql://192.168.1.65:3306/myDB";
private static final String user = "user";
private static final String pass = "userpass";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void connect(View v){
TextView tv = (TextView) findViewById(R.id.textView);
try{
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url,user,pass);
if(con!=null){
tv.setText("Connection Successfully");
}else
tv.setText("FAAAAIL ");
}catch (Exception e){
e.printStackTrace();
tv.setText(e.toString());
}
}
}
Related
I am trying to get an image from a url stored in a table but when I try to get the image the ImageView doesn't contain anything it is just blank.
In my code below I have used Picasso to get the picture:
public class Imageoffam extends AppCompatActivity {
private boolean success = false; // boolean
private ConnectionClass connectionClass;
public TextView tmtmt;
public ImageView dede;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_imageoffam);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
tmtmt = (TextView) findViewById(R.id.tomato) ;
dede = (ImageView) findViewById(R.id.dededede);
connectionClass = new ConnectionClass();
SyncData orderData = new SyncData();
orderData.execute("");
}
private class SyncData extends AsyncTask<String, String, String> {
String msg = "Success";
ProgressDialog progress;
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(Imageoffam.this, "Synchronising",
"Please Wait...", true);
}
#Override
protected String doInBackground(String... strings) {
try {
Connection conn = connectionClass.CONN();
if (conn == null) {
msg = "Please Check Your Connection";
success = false;
} else {
String dta = getIntent().getStringExtra("blala");
String query = "SELECT Images.Fimage,family.FName,family.FInfo,family.CID FROM Images INNER JOIN family ON family.FID = Images.FID WHERE family.FInfo = (N'" +dta+ "')";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
try {
Picasso.with(Imageoffam.this).load(rs.getString("Fimage")).into(dede);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
success = false;
}
return msg;
}
#Override
protected void onPostExecute(String msg) {
progress.dismiss();
Toast.makeText(Imageoffam.this, msg + "", Toast.LENGTH_LONG).show();
if (success == false) {
} else {
try {
} catch (Exception ex) {
}
}
}
}
It doesn't give any error message although it doesn't show the image in the ImageView.
Can someone please tell me what am I doing wrong?
Any help would be appreciated.
if you store image uri in db you need to setting uri on ImageView by
imageView.setImageUri(uri);
after get to uri from db
When using Picasso, no need of AsyncTask, just do:
Picasso.with(context).load(imageUri).into(ivBasicImage);
For example:
String imageUri = "https://i.imgur.com/tGbaZCY.jpg";
ImageView ivBasicImage = (ImageView) findViewById(R.id.ivBasicImage);
Picasso.with(context).load(imageUri).into(ivBasicImage);
You can also try Glide:
Glide.with(context).load(url).into(imageView);
Instead of the picasso method,
I recommend the local webview method.
This question already has answers here:
Android ECONNREFUSED (Connection refused)
(2 answers)
Closed 5 years ago.
Hello I am beginner to android.I want to make a database connection to mssql server in my pc. I found example on the net.
I think I have something wrong in connection ip or port. I guess syntax is wrong.
I get this log :
Network error IOException: failed to connect to /127.0.0.1 (port 1433) from /:: (port 55062): connect failed: ECONNREFUSED (Connection refused)
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 = "127.0.0.1:1433";
String classs = "net.sourceforge.jtds.jdbc.Driver";
String db = "DBAndroid1";
String un = "TestUser";
String password = "123";
Here is my MainActivity.java.
public class MainActivity extends AppCompatActivity {
ConnectionClass connectionClass;
EditText edtuserid, edtpass;
Button btnlogin;
ProgressBar pbbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectionClass = new ConnectionClass();
edtuserid = (EditText) findViewById(R.id.et_username);
edtpass = (EditText) findViewById(R.id.et_password);
btnlogin = (Button) findViewById(R.id.btn_Login);
pbbar = (ProgressBar) findViewById(R.id.pbbar);
pbbar.setVisibility(View.GONE);
btnlogin.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 isSuccess = false;
String userid = edtuserid.getText().toString();
String password = edtpass.getText().toString();
#Override
protected void onPreExecute() {
pbbar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String r) {
pbbar.setVisibility(View.GONE);
Toast.makeText(MainActivity.this,r,Toast.LENGTH_SHORT).show();
if(isSuccess) {
Toast.makeText(MainActivity.this,r,Toast.LENGTH_SHORT).show();
}
}
#Override
protected String doInBackground(String... params) {
if(userid.trim().equals("")|| password.trim().equals(""))
z = "Please enter User Id and Password";
else
{
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
String query = "select password from User";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs.next())
{
z = "Login successfull";
isSuccess=true;
}
else
{
z = "Invalid Credentials";
isSuccess = false;
}
}
}
catch (Exception ex)
{
isSuccess = false;
z = "Exceptions burda mi ";
}
}
return z;
}
}
}
#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).newInstance();
ConnURL = "jdbc:jtds:sqlserver://" + ip + ";"
+ "databaseName=" + db + ";user=" + un + ";password="
+ password + ";";
conn = DriverManager.getConnection(ConnURL);
} catch (SQLException se) {
Log.e("ERRO0", se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("ERRO1", e.getMessage());
} catch (Exception e) {
Log.e("ERRO2", e.getMessage());
}
return conn;
}
}
I hope you can help. Thank you.
Are you doing this from an emulator or your device? On your device make sure you are on the wi-fi and not using your cellular data. It needs to be on the same network. Your IP should be 10.0.2.2 not localhost (aka 127.0.0.1) as Android emulator is on a VM. As local host for the emulator is referring to the emulator itself not the actual localhost.
My class dose not have a abstract keyword before the class keyword in the class declaration, but when i tried to instantiate the class on an activity it tells me class is abstract; can not be instantiated.
This makes no sense because it doesn't look like an abstract class to me. please help me figer out what I'm doing wrong and how I can fix it
The error is at new ConnectionClass()
Here is the class ConnectionClass
final public class ConnectionClass {
String ip = "";
String classs = "net.sourceforge.jtds.jdbc.Driver";
String db = "tmseprd";
String un = "";
String password = "";
#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("ERRO", se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("ERRO", e.getMessage());
} catch (Exception e) {
Log.e("ERRO", e.getMessage());
}
return conn;
}
}
Here is the activity activity_connection
public class ConnectionActivity extends AppCompatActivity {
ConnectionClass connectionClass;
EditText edtuserid,edtpass;
Button btnlogin;
ProgressBar pbbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connection);
connectionClass = new ConnectionClass();
edtuserid = (EditText) findViewById(R.id.edtuserid);
edtpass = (EditText) findViewById(R.id.edtpass);
btnlogin = (Button) findViewById(R.id.btnlogin);
pbbar = (ProgressBar) findViewById(R.id.pbbar);
pbbar.setVisibility(View.GONE);
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DoLogin doLogin = new DoLogin();
doLogin.execute("");
}
});
}
I am assuming you are getting the error at new ConnectionClass().
There seems no need to have a final class. Add a constructor just to be sure also. You might have meant that you needed a static class with static methods.
Use this instead:
public class ConnectionClass {
String ip = "";
String classs = "net.sourceforge.jtds.jdbc.Driver";
String db = "tmseprd";
String un = "";
String password = "";
public ConnectionClass(){}
#SuppressLint("NewApi")
public Connection CONN() {
....
}
}
I need to build an android app for my final year project, (i am new to android development). Is there any idea to minimize the code or maybe separate into different classes.
I want to make my main activity shorter and cleaner for maintenance, and preferably if it can be coded using MVC architecture. There will be more UI components added later.
Thank you for ur attention.
public class MainActivity extends AppCompatActivity {
Button find_button;
EditText user_origin;
EditText user_destination;
private TextView json_output;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
find_button = (Button)findViewById(R.id.find_button);
json_output = (TextView)findViewById(R.id.json_output);
user_origin = (EditText)findViewById(R.id.user_origin);
user_destination = (EditText)findViewById(R.id.user_destination);
find_button.setOnClickListener(new View.OnClickListener(){
String origin;
String new_origin;
String destination;
String new_user_destination;
#Override
public void onClick(View v){
origin = user_origin.getText().toString();
new_origin = origin.replaceAll(" ", "+");
destination = user_destination.getText().toString();
new_user_destination = destination.replaceAll(" ", "+");
String link = "https://maps.googleapis.com/maps/api/directions/json?origin=" + new_origin + "&destination=" + new_user_destination + "&mode=transit&key=AIzaSyD83XCiGtJyo6Ln8c7yyyrQwmFDFZB_oiU";
//json_output.setText(link);
new JSONTask().execute(link);
}
});
}
public class JSONTask extends AsyncTask<String,String,String> {
#Override
protected String doInBackground(String... params){
HttpURLConnection connection = null;
BufferedReader reader = null;
try{
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while((line = reader.readLine()) != null ){
buffer.append(line);
}
String final_json = buffer.toString();
return buffer.toString();
} catch (MalformedURLException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
} finally {
if(connection != null) {
connection.disconnect();
}
try {
if(reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
json_output.setText("result:" +result);
}
}
}
You can separate your JSONTask as a simple class,and execute its task,then define an interface in this class to pass some message or data should be handled by other class,and add a parameter type is this interface for constructor and save it as a field.like this:
public class JSONTask extends AsyncTask<String,String,String>{
private OnHandleResult mResult;
private String[] mParams;
public JSONTask(OnHandleResult onHandleResult,String... params){
this.mResult = onHandleResult;
this.mParams = params;
}
protected String doInBackground(String... params){
//params is empty,get params from this.mParams
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
//json_output.setText("result:" +result);
this.mResult.handleResult(result);
}
public static interface OnHandleResult{
void handleResult(final String result);
}
}
then let your activity implement interface onHandleResult,and hanlde result:set text to textview:
public class MainActivity extends AppCompatActivity implements JSONTask.OnHandleResult{
void handleResult(final String result){
json_output.setText("result:" +result);
}
}
and execute task like this:
new JSONTask(this,link).execute();
Usually it's good practise to have 1 class per file.
You can make your MainActivity a bit more readable
public class MainActivity extends AppCompatActivity {
Button find_button;
EditText user_origin;
EditText user_destination;
private TextView json_output;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
find_button = (Button) findViewById(R.id.find_button);
json_output = (TextView) findViewById(R.id.json_output);
user_origin = (EditText) findViewById(R.id.user_origin);
user_destination = (EditText) findViewById(R.id.user_destination);
String link = build_link(user_origin, user_destination);
MyListener l = new MyListener(link);
find_button.setOnClickListener(l);
}
private String build_link(EditText user_origin, EditText user_destination) {
String origin = user_origin.getText().toString();
String new_origin = origin.replaceAll(" ", "+");
String destination = user_destination.getText().toString();
String new_user_destination = destination.replaceAll(" ", "+");
return "https://maps.googleapis.com/maps/api/directions/json?origin=" + new_origin + "&destination=" + new_user_destination + "&mode=transit&key=AIzaSyD83XCiGtJyo6Ln8c7yyyrQwmFDFZB_oiU";
}
by isolating your listener's implementation:
public class MyListener implements View.OnClickListener {
String link;
public MyListener(String link) {
this.link = link;
}
#Override
public void onClick(View v) {
new JSONTask().execute(link);
}
I did a TCP client on Java and works fine, but when I import the class to my Android project, it doesn't work.
Android code:
// ...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.SEND);
ssid = (EditText) findViewById(R.id.textSsid);
pass = (EditText) findViewById(R.id.textPass);
debugText = (EditText) findViewById(R.id.debugText);
cliente = new ClienteTCP();
debugText.setText("Version 1-prealpha");
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
demo(v);
}
});
}
public void demo(View view) {
cliente.configure(ssid.getText(), pass.getText());
CharSequence cs = cliente.sendMessage("Hola Mundo");
if ( cs != null)
debugText.setText(cs);
else
debugText.setText("ERROR OCURRED");
}
// ...
I always get the "ERROR OCURRED" message, I try to use another IPs, but all of them works fine on Java and not on android.
The class code:
private CharSequence SSID, pass;
private String HOST = "52.28.45.92"; // My external server i tried with localhot server too ...
// of course i have a server aplication running hahaha
private int PORT = 5000;
private Socket s;
private DataOutputStream oms;
// ...
public CharSequence sendMessage(String ms) {
DataInputStream ims;
CharSequence data = null;
try {
s = new Socket(HOST,PORT);
oms = new DataOutputStream(s.getOutputStream());
ims = new DataInputStream(s.getInputStream());
oms.writeUTF(ms+getFull());
data = ims.readUTF();
oms.close();
ims.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
I think it can be due to my emulator, any ideas? is the code wrong?
EDIT: Server code:
# ...
# Wrote on Python:
while 1:
data = conn.recv(BUFFER_SIZE)
if not data: break
print "received data:", data
conn.send(data+'\r\n')
conn.close()