My data is not inserting to database of webhost.
Here is my ActionActivity.java from where I will send data to the database.
import android.app.Activity;
import android.content.Context;
import android.provider.Settings;
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.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.InputStream;
public class ActionActivity extends Activity {
private String t;
TextView timer;
EditText e1,e2;
Button save;
static InputStream is = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_action);
Bundle time = getIntent().getExtras();
t = (String) time.get("com.example.masba.timemanagement.MESSAGE");
e1 = (EditText) findViewById(R.id.editText);
e1.setText(t, TextView.BufferType.EDITABLE);
e2 = (EditText) findViewById(R.id.editText2);
save = (Button) findViewById(R.id.save);
}
public void insert(View view){
String actionName = e1.getText().toString();
String time = e2.getText().toString();
Toast.makeText(this, "Data Inserting...", Toast.LENGTH_SHORT).show();
new SignupActivity(this).execute(actionName, time);
e1.setText("");
e2.setText("");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Now my SignupActivity.java Which extends Asynctask.
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class SignupActivity extends AsyncTask<String, Void, String> {
private Context context;
public SignupActivity(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String actionName = arg0[0];
String time = arg0[1];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?actioname=" + URLEncoder.encode(actionName, "UTF-8");
data += "&time=" + URLEncoder.encode(time, "UTF-8");
link = "http://masumalmasba.comli.com/insertdata.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
if (query_result.equals("SUCCESS")) {
Toast.makeText(context, "Data inserted successfully.", Toast.LENGTH_SHORT).show();
} else if (query_result.equals("FAILURE")) {
Toast.makeText(context, "Data could not be inserted.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Couldn't connect to remote database.", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, "Error parsing JSON data.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
}
}
}
Now my insertdata.php code is:
<?php
$servername="mysql6.000webhost.com";
$username = "a1871724_masum";
$password = "almasba012";
$dbname = "a1871724_actiont";
$conn = new mysqli($servername , $username , $password , $dbname);
if($conn->connect_error)
{
die("Connection Failed: ".$conn->connect_error);
}
$action = $_GET['actionname'];
$time = $_GET['time'];
$sql = "INSERT INTO actiontime (name,time) VALUES ('($action)','($time)')";
if($conn->query($sql)===TRUE){
echo "New record created succesfully";
}
else{
echo "Error";
mysql_close($conn);
}
?>
Related
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();
}
}
}
}
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. Because I have two records in my User table. But this code only gives me first record in table.
Here is ConnectionClass.java :
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";
#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;
}
}
Here is my MainActivity.java.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
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 Username from [User]";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
int columnCount = rs.getMetaData().getColumnCount();
System.out.println("Eleman sayisi: "+ columnCount);
if(rs.next())
{
String lastName = rs.getString("Username");
z = "Login successfull";
z = z + " " + lastName;
isSuccess=true;
}
else
{
z = "Invalid Credentials";
isSuccess = false;
}
}
}
catch (Exception ex)
{
isSuccess = false;
z = "Exceptions burda mi "+ ex;
}
}
return z;
}
}
}
I hope you can help. Thank you.
You have two records in table but you are using if(rs.next()) to fetch record which will return only single record.
Use for loop or while loop to get all records and iterate resultset in loop.
I'm trying to retrieve data from Facebook using graph Facebook, like Profile Pic, Gender, Age, Name, ID & Link, I'm getting Facebook Profile Pic only successfully but other won't retrieved. Please help!
MainActivity.java
package com.example.facebookprofile;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.facebookprofile.pictureAsync.onImageDownloaded;
import com.example.facebookprofile.profileAsync.profileImplement;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements profileImplement, onImageDownloaded {
ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onClick(View view){
EditText enterUsername = (EditText) findViewById(R.id.enterUsername);
String s = "https://graph.facebook.com/" + enterUsername.getEditableText().toString();
pictureAsync picTask = new pictureAsync(this);
profileAsync task = new profileAsync(this);
picTask.execute(s + "/picture?type=large");
picTask.delegate = this;
task.delegate = this;
task.execute(s);
}
public static User parseJSON(String jsonString) throws JSONException{
JSONObject top = new JSONObject(jsonString);
String name = "NA";
if(top.has("name"))
name = top.getString("name");
String username = top.getString("username");
String id = "NA";
if(top.has("id"))
id = top.getString("id");
String gender = "NA";
if(top.has("gender"))
gender = top.getString("gender");
String link = "https://www.facebook.com/"+username;
if(top.has("link"))
link = top.getString("link");
User output = new User(name, username, id, gender, link);
return output;
}
#Override
public void update(User user) {
// TODO Auto-generated method stub
if(user == null){
Toast t = Toast.makeText(this, "Invalid username", Toast.LENGTH_SHORT);
t.show();
}
else{
TextView name = (TextView) findViewById(R.id.name);
TextView id = (TextView) findViewById(R.id.id);
TextView gender = (TextView) findViewById(R.id.gender);
TextView link = (TextView) findViewById(R.id.link);
name.setText(user.name);
id.setText(user.id);
gender.setText(user.gender);
link.setText(user.link);
}
}
#Override
public void setImage(Bitmap bitmap) {
// TODO Auto-generated method stub
if(bitmap != null){
ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setImageBitmap(bitmap);
}
}
}
pictureAsync.java
package com.example.facebookprofile;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
public class pictureAsync extends AsyncTask<String, Integer, Bitmap> {
Context context;
onImageDownloaded delegate;
public interface onImageDownloaded{
public void setImage(Bitmap bitmap);
}
public pictureAsync(Context context) {
this.context = context;
}
#Override
protected Bitmap doInBackground(String... params) {
String picUrl = params[0];
try {
URL url = new URL(picUrl);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if(delegate!=null)
delegate.setImage(result);
}
}
profileAsync.java
package com.example.facebookprofile;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import javax.net.ssl.HttpsURLConnection;
import org.json.JSONException;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
public class profileAsync extends AsyncTask<String, Integer, User> {
profileImplement delegate;
Context context;
ProgressDialog dialog;
public profileAsync(Context context) {
this.context = context;
}
#Override
public void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(context);
dialog.setMessage("Loading...Please wait");
dialog.show();
}
public interface profileImplement{
public void update(User user);
}
#Override
protected User doInBackground(String... arg) {
String user = arg[0];
try {
URL url = new URL(user);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream input = connection.getInputStream();
if(input == null) return null;
Scanner networkScanner = new Scanner(input);
StringBuffer buffer = new StringBuffer();
int count = 0;
while(networkScanner.hasNext()){
String line = networkScanner.next();
count += line.length();
//publishProgress(count);
buffer.append(line);
}
networkScanner.close();
return MainActivity.parseJSON(buffer.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(User result) {
dialog.dismiss();
if(delegate != null)
delegate.update(result);
}
// protected void onProgressUpdate(Integer... values) {
// // TODO Auto-generated method stub
// super.onProgressUpdate(values);
// dialog.setMessage("downloaded: " + values[0]);
// }
}
User.java
package com.example.facebookprofile;
public class User {
String name;
String username;
String id;
String gender;
String link;
User(String name, String username , String id , String gender , String link){
this.name = name;
this.username = username;
this.id = id;
this.gender = gender;
this.link = link;
}
}
It is a feature gone deprecated.
If I run my app in the emulator my app crashes immediately. I get the error 'Caused by: java.lang.IllegalArgumentException: host=null, port=4444.' Logcat says the error comes from InetSocketAdress. This is my server code:
package com.imptmd.charliemacdonald.desleutelaar_v3;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
/**
* Created by Charlie on 26-3-2015.
*/
public class Server extends AsyncTask<Void, Void, String> {
private String message;
private String ip;
public static int port = 4444;
private String serverResponse = null;
public Server(String ip, int port, String message ) {
super();
//IP, Port en bericht om naar server te sturen
this.message = message;
this.ip = ip;
this.port = port;
}
#Override
protected String doInBackground(Void... params) {
try {
Socket serverSocket = new Socket();
serverSocket.connect(new InetSocketAddress(this.ip, this.port), 4444);
this.sendMessage(message, serverSocket);
InputStream input;
try {
input = serverSocket.getInputStream();
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(input));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line);
}
responseStreamReader.close();
this.serverResponse = stringBuilder.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Response: " + serverResponse);
} catch (UnknownHostException e) {
Log.d("debug", "can't find host");
} catch (SocketTimeoutException e) {
Log.d("debug", "time-out");
} catch (IOException e) {
e.printStackTrace();
}
return serverResponse;
}
private void sendMessage(String message, Socket serverSocket) {
OutputStreamWriter outputStreamWriter = null;
try {
outputStreamWriter = new OutputStreamWriter(serverSocket.getOutputStream());
} catch (IOException e2) {
e2.printStackTrace();
}
if (outputStreamWriter != null) {
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
PrintWriter writer = new PrintWriter(bufferedWriter, true);
writer.println(message);
}
}
}
The code of the class where the user can fill in the IP:
package com.imptmd.charliemacdonald.desleutelaar_v3;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.concurrent.ExecutionException;
public class GebruikerIP extends Activity {
private Boolean serverCheck;
#Override
protected void onCreate(Bundle savedInstanceState) {
setTitle("Slotenbedrijf De Sleutelaar");
//Check voor internet verbinding
if(NetwerkCheck.isInternetAvailable(GebruikerIP.this))
{
}
else
{
Toast.makeText(GebruikerIP.this, "Er is helaas geen internetverbinding geconstateerd, daarom wordt nu de laatst opgehaalde informatie getoond.!", Toast.LENGTH_LONG).show();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gebruikerip);
Button ipButton = (Button) findViewById(R.id.serverbutton);
ipButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
verbindServer();
}
});
//Enter key afvangen
EditText ipInvoer = (EditText) findViewById(R.id.ipinvoeren);
ipInvoer.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
switch(keyCode) {
case KeyEvent.KEYCODE_ENTER:
verbindServer();
break;
default:
return false;
}
return true;
}
});
}
//server connectie maken voor ophalen van diensten
public void verbindServer() {
TextView ipVeld = (TextView) findViewById(R.id.ipinvoeren);
String ip = ipVeld.getText().toString();
Log.i("ip", ip);
String response = null;
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("slotenlijst", "");
} catch (JSONException e) {
e.printStackTrace();
}
try {
try {
response = new Server(ip,
4444, jsonObject.toString()).execute().get();
//exceptions afvangen
} catch (InterruptedException e)
{
}
} catch (ExecutionException e1)
{
}
if (response == null) {
serverCheck = false;
Toast.makeText(this, "Verbinden met server mislukt, staat server aan?", Toast.LENGTH_LONG).show();
} else {
//doorgaan naar MainActivity
serverCheck = true;
HoofdschermFragment.serverIp = ip;
Intent startApp = new Intent(this, MainActivity.class);
startActivity(startApp);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_gebruiker_ip, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
}
I can't find out how I can fix this error. Help would me appreciated. Thanks!
change it to
InetAddress inetServer = InetAddress.getByName(IP);
than
Socket socket = new Socket(inetServer, devicePort);
and if you are using for Server Socket than use below line
ServerSocket socket = new ServerSocket(devicePort,int backlognumber, inetServer);
package com.example.m2mai;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class RetrieveActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retrieve);
}
public void getStream(View v)
{
new MyAsyncTask().execute();
}
private class MyAsyncTask extends AsyncTask<String, Void, String>
{
ArrayList<String> mNameList = new ArrayList<String>();
public ArrayList<String> atList=new ArrayList<String>();
public ArrayList<String> dataList=new ArrayList<String>();
protected String doInBackground(String... params)
{
return getData();
}
public long getDateTo()
{
EditText toText = (EditText)findViewById(R.id.dateTo);
String To = toText.getText().toString();
DateFormat dateFormatTo = new SimpleDateFormat("dd/MM/yyyy");
Date dateTo = null;
try {
dateTo = dateFormatTo.parse(To);
} catch (java.text.ParseException e) {
.runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),"Please key in the correct input", Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
}
long timeTo = dateTo.getTime();
new Timestamp(timeTo);
return timeTo/1000;
}
protected String getData()
{
String toTS = ""+getDateTo();
String decodedString="";
String returnMsg="";
String request = "http://api.carriots.com/devices/defaultDevice#eric3231559.eric3231559/streams/?order=-1&max=10&at_to="+toTS;
URL url;
HttpURLConnection connection = null;
try {
url = new URL(request);
connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("carriots.apikey", "1234567");
connection.addRequestProperty("Content-Type", "application/json");
connection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((decodedString = in.readLine()) != null)
{
returnMsg+=decodedString;
}
in.close();
connection.disconnect();
JSONObject nodeRoot = new JSONObject(returnMsg);
JSONArray res = nodeRoot.getJSONArray("result");
for (int i = 0; i < res.length(); i++)
{
JSONObject childJSON = res.getJSONObject(i);
if (childJSON.get("data")!=null)
{
String value = childJSON.getString("data");
dataList.add(value);
JSONObject node=new JSONObject(value);
atList.add(node.get("temperature").toString());
}
}
}
catch (Exception e)
{
e.printStackTrace();
returnMsg=""+e;
}
return returnMsg;
}
protected void onPostExecute(String result)
{
for(int i = 0; i < atList.size(); i++)
{
ListView mainListView = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(RetrieveActivity.this,android.R.layout.simple_list_item_1,mNameList);
mainListView.setAdapter(mArrayAdapter);
mNameList.add(atList.get(i).toString());
mArrayAdapter.notifyDataSetChanged();
}
Toast.makeText(getApplicationContext(),result, Toast.LENGTH_SHORT).show();
EditText myData1=(EditText)findViewById(R.id.editText1);
myData1.setText(atList.get(0));
}
}
}
How can I actually display a toast without stoping it? Whenever it falls into the catch it is not responding.
............................................................................................................................................................................................................................................................................
If you are using try-catch in a worker thread and want to display Toast, then I am afraid it is not going to work. You will have to do it in Main(UI) thread.
Try following:
try {
dateTo = dateFormatTo.parse(To);
}
catch (java.text.ParseException e) {
your_activity_context.runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),"Please key in the correct input", Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
}
Try following:
In getDateTo():
try {
dateTo = dateFormatTo.parse(To);
} catch (java.text.ParseException e) {
runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),"Please key in the correct input", Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
return -1L; // attention here
}
In getData():
long dateTo = -1L;
if((dateTo = getDateTo()) == -1L){
return null;
}
String toTS = "" + getDateTo();
In onPostExecute:
if(result == null) {
return;
}
Make boolean flag = false; globally.
Inside catch block make flag = true;
Run Toast inside an if block like
if (flag) {
Toast.makeText(this, "Sorry, Couldn't find anything!", Toast.LENGTH_LONG).show();
}
inside your onclick method.