I am trying to get an Android Studio app to connect to a remote server hosted on "hostbuddy". Here is the code (when sending data the error is "Connection goes wrong 2") making me guess there is something wrong with the DB_URL. I tried changing the url in many ways, none worked. If it would help I could also post the logcat.
EDIT : I fixed it, i forgot to add the module for the connector for MySQl, works like a charm now ^_^
package com.example.battl.qr2;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class Register extends AppCompatActivity {
TextView textView;
Button button;
EditText editText;
private static final String DB_URL= "jdbc:mysql://mysql6002.site4now.net/db_a37d85_mydb:3306";
private static final String USER = "X";
private static final String PASS = "X";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
textView=(TextView) findViewById(R.id.textView);
editText=(EditText) findViewById(R.id.editText);
}
public void btnConn(View view)
{
Send objsend = new Send();
objsend.execute("");
}
private class Send extends AsyncTask<String,String,String>
{
String msg = "";
String text = editText.getText().toString();
#Override
protected void onPreExecute() {textView.setText("Please Wait Inserting");}
#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 ex (col1) VALUES ('"+text+"') ";
Statement stmt = conn.createStatement();
stmt.executeUpdate(query);
msg = "Inserted successfully";
}
conn.close();
}
catch (Exception e)
{
msg="Connection goes wrong 2";
e.printStackTrace();
}
return msg;
}
#Override
protected void onPostExecute(String msg) {textView.setText(msg);}
}
}
Related
I'm a beginner and I have been following several tutorials in order to parse JSON. I am just about to compile and try to run for the first time but when I tried to make an object of my java class and have the process run when the button "click" is triggered, I get an error stating " Cannot resolve symbol "fetchData" "
package com.example.h.arbitrage;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
Button click;
public static TextView data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
click = findViewById(R.id.button);
data = findViewById(R.id.fetcheddata);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fetchData process = new fetchData();
((fetchData) process).execute();
}
});
}
}
I'm also including the code for fetchData.java in case there's something in there that's causing this.
I've looked all over for the answer and it might be very obvious but I don't even have the terminology to properly research this...
import android.net.UrlQuerySanitizer;
import android.os.AsyncTask;
import com.example.h.arbitrage.MainActivity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class fetchData extends AsyncTask<Void,Void,Void> {
String data = "";
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("https://");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line ="";
while(line != null){
line = bufferedReader.readLine();
data = data + line;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
MainActivity.data.setText(this.data);
}
}
Thanks in advance for any help.
When tapping an image (from a previous activity) I get to this activity (where I pass the clientid) that reads a JSONArray and use a setter to set the nick.
I then use a getter to do a textview setText.
The problem is that the first time no nick is set. When I go back to the previous activity and tap the same image again, only then the nick is set.
Why isn't the nick displayed from the first time.
(ps: I'm quite new to Java/Android Studio)
package com.smartvibes.smartbeat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class profileViewActivity extends AppCompatActivity {
RequestQueue rs;
String url, id, nick, age, city, mainpic, numpics, extrapic0, extrapic1, extrapic2, extrapic3, extrapic4, extrapic5;
TextView profileIntro;
static String pnick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_view);
Bundle getProfileId = getIntent().getExtras();
if (getProfileId == null) {
return;
}
String profileid = getProfileId.getString("profileid");
url = "https://www.smartvibes.be/profiles/api/profileview.php?id=" + profileid;
rs = Volley.newRequestQueue(this);
sendjsonrequest();
profileIntro = (TextView) findViewById(R.id.profileIntro);
profileIntro.setText(getPnick());
}
public void sendjsonrequest() {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
setPnick(response.getString("nick"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
rs.add(jsonObjectRequest);
}
public static void setPnick(String nick) {
pnick = nick;
}
public static String getPnick(){
return pnick;
}
}
Because sendjsonrequest is an async call
You need to update textView in onResponse Method itself, like below
setPnick(response.getString("nick"));
profileIntro.setText(getPnick());
This question already has answers here:
error reading xml string in java file [duplicate]
(2 answers)
Closed 5 years ago.
Error:(90, 20) error: incompatible types: int cannot be converted to String
How to fix the error
in lineR.string.Invalid_city_name
using the method
getstring(R. string.Invalid_city_name)
the same error what is wrong?
status="success";
}else{
status=R.string.Invalid_city_name;
}
full Code:
package com.nbdev.app.weatherapp.json;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONObject;
import android.app.Dialog;
import android.content.Context;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.nbdev.app.weatherapp.ActivityMain;
import com.nbdev.app.weatherapp.adapter.ItemLocationAdapter;
import com.nbdev.app.weatherapp.data.Constant;
import com.nbdev.app.weatherapp.data.DatabaseManager;
import com.nbdev.app.weatherapp.data.GlobalVariable;
import com.nbdev.app.weatherapp.model.City;
import com.nbdev.app.weatherapp.R;
import com.nbdev.app.weatherapp.model.ForecastResponse;
import com.nbdev.app.weatherapp.model.ItemLocation;
import com.nbdev.app.weatherapp.model.WeatherResponse;
public class JSONLoader extends AsyncTask<String, String, ItemLocation>{
private JSONParser jsonParser = new JSONParser();
private String jsonWeather = null,
jsonForecast= null,
status="null";
private Context ctx;
private LinearLayout lyt_form;
private LinearLayout lyt_progress;
private TextView tv_message;
private Dialog dialog;
private DatabaseManager db;
private GlobalVariable global;
private ActivityMain act;
public JSONLoader(ActivityMain act, LinearLayout lyt_form, LinearLayout lyt_progress, TextView tv_message, Dialog dialog) {
this.act=act;
this.ctx=act.getApplicationContext();
this.lyt_form=lyt_form;
this.lyt_progress=lyt_progress;
this.tv_message=tv_message;
this.dialog=dialog;
global = (GlobalVariable) act.getApplication();
db = new DatabaseManager(act);
}
#Override
protected void onPreExecute() {
lyt_form.setVisibility(View.GONE);
lyt_progress.setVisibility(View.VISIBLE);
super.onPreExecute();
}
#Override
protected ItemLocation doInBackground(String... params) {
ItemLocation itemLocation = new ItemLocation();
try {
Thread.sleep(50);
List<NameValuePair> param = new ArrayList<NameValuePair>();
City city = db.getWordsFormAutocomplate(params[0]);
if(city!=null){
itemLocation.setId(city.getId());
itemLocation.setName(city.getName());
itemLocation.setCode(city.getCode());
String url_weather = Constant.getURLweather(city.getId());
String url_forecast = Constant.getURLforecast(city.getId());
JSONObject json_weather = jsonParser.makeHttpRequest(url_weather,"POST", param);
JSONObject json_forecast = jsonParser.makeHttpRequest(url_forecast,"POST", param);
jsonWeather = json_weather.toString();
jsonForecast = json_forecast.toString();
itemLocation.setJsonWeather(jsonWeather);
itemLocation.setJsonForecast(jsonForecast);
status="success";
}else{
status=(R.string.Invalid_city_name();
}
} catch (Exception e) {
status = e.getMessage();
e.printStackTrace();
}
return itemLocation;
}
protected void onPostExecute(ItemLocation result) {
lyt_form.setVisibility(View.VISIBLE);
lyt_progress.setVisibility(View.GONE);
if(status.equals("success")){
global.saveLocation(result);
act.refreshList();
dialog.dismiss();
}
tv_message.setText(status);
//Toast.makeText(ctx, status, Toast.LENGTH_LONG).show();
};
}
You need a context/Activity to get string from your resources.
change this:
status=R.string.Invalid_city_name;
to this
status=act.getString(R.string.Invalid_city_name);
I'm fairly new to Android coding and I'm trying to create app that inserts some info into my MySQL DB. I've found a lot of tutorials and tips on web and created lite app to try procedures. Everything compiles OK, app runs and it seems to send data successfully. But in fact, no data appears in my table.
Here's my PHP code android_add.php:
<?php
$con = mysqli_connect(localhost, user, psswd, name); //those works
mysqli_set_charset($con, "utf8"); //working with special symbols
$name = $_POST['name']; //get name & author from App
$author = $_POST['author'];
$sql = "insert into kniha_test (k_autor_pr,k_nazev) values ('$name','$address')";
if(mysqli_query($con,$sql)){
echo 'success';
} else {
echo 'failure';
}
mysqli_close($con);
?>
And here's my MainActivity.java:
import android.content.ContentValues;
import android.os.AsyncTask;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private EditText editTextName;
private EditText editTextAuthor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextAuthor = (EditText) findViewById(R.id.editTextAuthor);
}
public void insert (View view){
String name = editTextName.getText().toString();
String author = editTextAuthor.getText().toString();
insertToDatabase(name,author);
}
protected void insertToDatabase(String name, String author){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
String name;
String author;
public void saveNameAut(String name, String author){
this.name = name;
this.author = author;
name = editTextName.getText().toString();
author = editTextAuthor.getText().toString();
}
#Override
protected String doInBackground(String... params){
String paramName = params[0];
String paramAuthor = params[1];
ContentValues values = new ContentValues();
values.put("name", this.name);
values.put("author", this.author);
String addUrl = "http://glaserproject.com/knihovna_kyber/android/android_add.php";
try {URL url = new URL(addUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
System.out.println("Response Code: " + conn.getResponseCode());
} catch (IOException e){};
return "Succes";
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
TextView textViewResult = (TextView) findViewById(R.id.textViewResult);
textViewResult.setText("inserted");
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(name, author);
}
}
As I said, I'm just beginner, so there may be something really stupid, but I can't figure out what. And there can be some trash lines from different tries. PHP code should be OK, I'm using practically the same to insert from HTML, so I'm guessing, there is problem in my Java code.
I will be really thankful for advices/responses.
Thanks!
PS: Response code I'm getting is 200.
You are sending null values through AsyncTask
Have you printed the values that you are sending through
try this
protected void insertToDatabase(String name, String author){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
String cName=name;
String cAuthor=author;
#Override
protected String doInBackground(String... params){
ContentValues values = new ContentValues();
values.put("name", cName);
values.put("author", cAuthor);
String addUrl = "http://glaserproject.com/knihovna_kyber/android/android_add.php";
try {URL url = new URL(addUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
System.out.println("Response Code: " + conn.getResponseCode());
} catch (IOException e){};
return "Succes";
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
TextView textViewResult = (TextView) findViewById(R.id.textViewResult);
textViewResult.setText("inserted");
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(name, author);
}
try again and let me know if it solves your problems....
I created an Android Application that connects to a local MySQL database to retrieve some sample data through JDBC.
When i run the application with the emulator,it works fine and loads the data.
When I run the application from my device,it freezes on loading the data,without errors from the logcat.
Here's the code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener{
Button bottone;
boolean connected = false;
private TextView nome1;
private TextView cognome1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottone = (Button)findViewById(R.id.button1);
bottone.setOnClickListener(this);
nome1 = (TextView) findViewById(R.id.text_name);
cognome1 = (TextView) findViewById(R.id.text_surname);
}
class ConnectAsync extends AsyncTask<String, Void, String> {
private String name;
private String surname;
private ProgressDialog myProgress;
#Override
protected void onPreExecute()
{
super.onPreExecute();
myProgress = ProgressDialog.show(MainActivity.this, "Wait", "Loading..");
}
#Override
protected String doInBackground(String... urls) {
String url = "jdbc:mysql://192.168.56.1/prova";
String user = "myuser";
String password = "mypsw";
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(url,user,password);
} catch (ClassNotFoundException e) {
System.out.println("Driver non caricato");
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
System.out.println("Errore con url e credenziali!");
}
if(connection!= null)
{System.out.println("Connessione riuscita!");
connected = true;}
ResultSet rs = null;
try {
Statement stmt = connection.createStatement();
String sql = "SELECT NOME,COGNOME FROM amici";
rs = stmt.executeQuery(sql);
if(!rs.next())
{System.out.println("Vuota");}
else
{
do{
name = rs.getString("NOME");
surname = rs.getString("COGNOME");
}while(rs.next());}
} catch (SQLException e) {
System.out.println("Query error");
}
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(connected)
return "Connessione riuscita";
else return "Connessione non riuscita";
}
#Override
protected void onPostExecute(String result)
{ myProgress.dismiss();
if(result.equals("Connessione riuscita"))
{Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
nome1.setText(name);
cognome1.setText(surname);}
else
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
}
}
public void connectToDB(View view)
{
ConnectAsync task = new ConnectAsync();
task.execute();}
#Override
public void onClick(View v) {
connectToDB(v);
}
}
The IP address i used in the JDBC string is the one i got typing "ipconfig" in windows cmd (IPv4).
The app simply shows a progress dialog until the connection is up,and then retrieves the data from the database putting it into two textviews.
As i said,when i try to connect using the Android Emulator it connects and runs fine,but when i run the application on my Device the application freezes at getting connection (progress dialog keeps loading) and no errors are given in the logcat.
I checked the minimum SDK required,and it matches with my phone Android version.
I think it's something related to the way MySQL database handles the connection requests from the emulator and from the device...any help is appreciated,thanks.
P.S: MySQL configuration file (my.ini) has the following parameters:
....
[mysqld]
bind-address= *
# skip-networking
...
...
wait_timeout = 30
interactive_timeout = 30
connect_timeout = 30