How to connect to phpmyadmin database using OkHttp3 in Android [duplicate] - android

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I’m new to Android, in order to prepare for my last school exam, I was asked to put an Android application solution using an external database on phpmyadmin ( wampserver).
My connection is done in the MainActivity file, using OkHttp3 and overriding AsyncTask with a request on an external php file for the authentification.
After a few days of work the connection still doesn’t work and my tests are coming soon, every launch of the android application is in debug mode and here are my error logs when i'm trying to connect :
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.brobert.biorelai, PID: 6002
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:354)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
at java.util.concurrent.FutureTask.run(FutureTask.java:271)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String okhttp3.Response.toString()' on a null object reference
at com.example.brobert.biorelai.MainActivity$BackTaskAuthentification.doInBackground(MainActivity.java:76)
at com.example.brobert.biorelai.MainActivity$BackTaskAuthentification.doInBackground(MainActivity.java:46)
at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) 
at java.lang.Thread.run(Thread.java:764) 
I/Process: Sending signal. PID: 6002 SIG: 9
Disconnected from the target VM, address: 'localhost:8600', transport:
'socket'
I already tried to add the internet permission via the AndroidManifest.xml :
<uses-permission android:name="android.permission.INTERNET"/>
To add the okhttp3 dependencies and put the proxy option on auto-detect.
MoreOver with the log function i verified that my EditText was working and my variable request too.
I think the error is on the line 70-71 of my MainActivity file :
response = client.newCall(request).execute();
responseStr = response.body().toString();
My MainActivity File code :
package com.example.brobert.biorelai;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View.OnClickListener;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import okhttp3.*;
public class MainActivity extends AppCompatActivity {
String responseStr;
OkHttpClient client = new OkHttpClient();
String textLogin1;
String mdp1;
Response response;
RequestBody formBody;
Request request;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button buttonValiderAuthentification = (Button)
findViewById(R.id.button2);
buttonValiderAuthentification.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View v){
new BackTaskAuthentification().execute();
}
});
}
private class BackTaskAuthentification extends AsyncTask<Void, Void,
Void> {
#Override
protected void onPreExecute() {
final EditText textLogin = findViewById(R.id.login1);
final EditText textMdp = findViewById(R.id.mdp1);
textLogin1 = textLogin.getText().toString();
mdp1 = textMdp.getText().toString();
}
#Override
protected Void doInBackground(Void... params){
try {
formBody = new FormBody.Builder()
.add("login", textLogin1)
.add("mdp", mdp1)
.build();
request = new Request.Builder()
.url("http://127.0.0.1/bio- relais/controleurMobil/json.php")
.post(formBody)
.build();
response = client.newCall(request).execute();
responseStr = response.body().toString();
} catch (Exception e) {
Log.d("test", textLogin1);
Log.d("test1", mdp1);
Log.d("test3", request.toString());
Log.d("test2", response.toString());
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (responseStr.compareTo("false") != 0){
try {
JSONObject membre = new JSONObject(responseStr);
String nom = membre.getString("nomM");
Intent intent = new Intent(MainActivity.this,
MainProducteurActivity.class);
intent.putExtra("membre", membre.toString());
startActivity(intent);}
catch(JSONException e){
Toast.makeText(MainActivity.this, "Erreur de connexion !",
Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(MainActivity.this, "Login ou mot de
passe non valide !",
Toast.LENGTH_SHORT).show();
}
}
}
}
A request is made on a local url http:///127.0.0.1/bio-relais/controleurMobil/json.php containing the code :
require_once '. /lib/autoloadMobil.php';
print(json_encode(MembreDAO::authentication($_POST['login'],
$_POST['mdp'])));
to pass the login and mdp of my Text edit in my method of the class MembreDao "authentification" containing the code :
public static function authentification($login, $mdp){
try{
$sql="select login, nomM ,prenomM
from MEMBRE
where login = :login
and mdp = :mdp ";
$requetePrepa = DBConnex::getInstance()->prepare($sql);
$mdp = md5($mdp);
$requetePrepa->bindParam("login", $login);
$requetePrepa->bindParam("mdp", $mdp);
$requetePrepa->execute();
$reponse = $requetePrepa->fetch(PDO::FETCH_ASSOC);
}catch(Exception $e){
$reponse = "";
}
return $reponse;
}
The expected result is a working authentification allowing the user present in the database to access to the interface of the MainProducteurActivity.
Thank you very much in advance for your help.

I finally found the problem, i was trying to connect to my localhost personal computer url on the avd with :
.url("http://127.0.0.1/bio- relais/controleurMobil/json.php")
But for the avd the localhost url of my json.php file is :
.url("http://10.0.2.2/bio-relais/controleurMobil/json.php")
( Localhost for avd = 10.0.2.2 ) .

Related

Unable to connect to Oracle 11g database using JDBC on Android

I'm trying to connect my Android app to Oracle Database Express Edition 11g hosted on my laptop. I'm testing the app on my phone with its hotspot ON to which the laptop is connected via WiFi.
I've added ojdbc14.jar to app/libs directory and selected Add as Library option on it through Android Studio.
I'm getting the following errors:
Rejecting re-init on previously-failed class java.lang.Class<oracle.jdbc.pool.OracleDataSource>: java.lang.NoClassDefFoundError: Failed resolution of: Ljavax/naming/Referenceable;
Caused by: java.lang.ClassNotFoundException: Didn't find class "javax.naming.Referenceable" on path: DexPathList
W/System.err: java.sql.SQLException: Io exception: The Network Adapter could not establish the connection
P.s. I know using a server is a better approach. Doing this for a client who wants to use it in a secure private network and they don't want to host a separate server for the database connection.
I read elsewhere that I need to use Async task for connecting JDBC but I'm not sure how; consider me a beginner. All other answers I found related to this keep going off topic. I just want to know how to make JDBC work on Android, considering the risks.
Here's my MainActivity.java:
package com.absingh.apptest;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MainActivity extends AppCompatActivity {
private static final String DEFAULT_DRIVER = "oracle.jdbc.driver.OracleDriver";
private static final String DEFAULT_URL = "jdbc:oracle:thin:#192.168.42.49:1521:XE";
private static final String DEFAULT_USERNAME = "myusername";
private static final String DEFAULT_PASSWORD = "mypassword";
private Connection connection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
TextView tv = (TextView) findViewById(R.id.hello);
try {
this.connection = createConnection();
Toast.makeText(MainActivity.this, "Connected",
Toast.LENGTH_SHORT).show();
Statement stmt=connection.createStatement();
StringBuffer stringBuffer = new StringBuffer();
ResultSet rs=stmt.executeQuery("select * from testtable");
while(rs.next()) {
stringBuffer.append( rs.getString(1)+"\n");
}
tv.setText(stringBuffer.toString());
connection.close();
}
catch (Exception e) {
Toast.makeText(MainActivity.this, ""+e,
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
public static Connection createConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException {
Class.forName(driver);
return DriverManager.getConnection(url, username, password);
}
public static Connection createConnection() throws ClassNotFoundException, SQLException {
return createConnection(DEFAULT_DRIVER, DEFAULT_URL, DEFAULT_USERNAME, DEFAULT_PASSWORD);
}
}
Nevermind, I figured it out.
The code in the question works fine if you add this above the application tag in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
I'll leave the question be, in case someone else gets the same problem.

Dictionary app using Oxford Dictionary API

I am trying to make a dictionary application using Oxford Dictionary api. There is something wrong with my code JSON. Can anyone tell me how do I extract only the definition of the searched word, rather getting the whole JSON file
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity {
private static final String APP_ID= "59028fc6";
private static final String API_KEY = "ad3e310307d7b2f8bf474c45e1efd01f";
private static final String TAG = MainActivity.class.getSimpleName();
private OkHttpClient okHttpClient;
private EditText textInput;
private Button submitButton;
private TextView definitionView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize ok http
okHttpClient = new OkHttpClient();
textInput = findViewById(R.id.textInput);
submitButton = findViewById(R.id.submitButton);
definitionView = findViewById(R.id.textMeaning);
submitButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
findMeaningOfEnteredWord();
}
});
}
private void findMeaningOfEnteredWord() {
String word = textInput.getText().toString();
if (word.isEmpty()) {
Toast.makeText(this, "Nothing entered", Toast.LENGTH_SHORT).show();
return;
}
// create url from the word
String lowerCaseWord = word.toLowerCase();
String httpRequestUrl = "https://od-api.oxforddictionaries.com:443/api/v1/entries/en/" + lowerCaseWord;
// make request with REST url
new RequestAsyncTask().execute(httpRequestUrl);
}
private class RequestAsyncTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
String requestUrl = params[0];
Request request = new Request.Builder()
.url(requestUrl)
.addHeader("Accept", "application/json")
.addHeader("app_id", APP_ID)
.addHeader("app_key", API_KEY)
.build();
Response response = null;
try {
response = okHttpClient.newCall(request).execute();
return response.body().string();
} catch (IOException ex) {
Log.e(TAG, "caught error: " + ex.getMessage());
}
return "";
}
#Override
protected void onPostExecute(String result) {
try {
JSONObject responseAsJson = new JSONObject(result);
JSONArray results = responseAsJson.getJSONArray("results");
if (results.length() > 0) { // valid definitions were found
String lexicalEntries = results.getJSONObject(0).getString("lexicalEntries");
definitionView.setText(lexicalEntries);
}
Log.d(TAG, " " + responseAsJson.toString());
} catch (Exception ex) {
Log.d(TAG, "exception during json parsing: " + ex.getMessage());
}
}
}
}
JSON:
{"id":"aeroplane",
"language":"en",
"lexicalEntries": [
{
"entries": [{"etymologies":["late 19th century: from French aéroplane, from aéro- ‘air’ + Greek -planos ‘wandering’"],
"grammaticalFeatures":[{"text":"Singular","type":"Number"}],
"homographNumber":"000",
"senses":[{"crossReferenceMarkers":["North American term airplane"],
"crossReferences":[{"id":"airplane","text":"airplane","type":"see also"}],
"definitions":["a powered flying vehicle with fixed wings and a weight greater than that of the air it displaces."],
"domains":["Aviation"],
"id":"m_en_gbus0013220.005",
"regions":["British"],
"short_definitions":["powered flying vehicle with fixed wings"],
"thesaurusLinks":[{"entry_id":"plane","sense_id":"t_en_gb0011151.001"}]}]}],"language":"en","lexicalCategory":"Noun","pronunciations":[{"audioFile":"http:\/\/audio.oxforddictionaries.com\/en\/mp3\/aeroplane_gb_2.mp3","dialects":["British English"],"phoneticNotation":"IPA","phoneticSpelling":"ˈɛːrəpleɪn"}],"text":"aeroplane"}],
"type":"headword","word":"aeroplane"
}
Modify these lines :
String lexicalEntries = results.getJSONObject(0).getString("lexicalEntries");
definitionView.setText(lexicalEntries);
to :
String definition = results.getJSONObject(0).getString("lexicalEntries")
.getJSONArray("entries").getJSONObject(0).getJSONArray("senses")
.getJSONObject(0).getJSONArray("definitions").getString(0);
definitionView.setText(definition);
Of course you may need to modify your UI based on the number of definitions a word has.
Also, you should probably consider using POJOs instead of directly dealing with the JSON response.
I'd recommend Jackson or GSON for doing this.
String definitions=results.getJSONArray("lexicalEntries")
.getJSONObject(0)
.getJSONArray("entries")
.getJSONObject(0)
.getJSONArray("senses")
.getJSONArray("definitions")
.get(0)
So , The thing is , There are a lot of gaps in the JSON for different words .
Which means a word may have an array of "synonyms" but others don't , So in your code you are trying to reach something that doesn't actually exist (a NULL value) which is likely to throw an exception every time you search for a word that the JSON returned doesn't match the JSON you are expecting , Because there are missing (NULL) values .
The app I made using oxford dictionary required a lot of work just to make sure there is no thrown exception .
I used retrofit with moshi converter factory , And then Do the following :
1-In your custom classes , Make sure you annotate every data member with
#Json and provide the name of the keys in the JSON of oxford
2-make sure that every declared type is nullable , including both List and the type inside of it
You'll then be able to get the result , And Now comes the part where you handle evey call that may be null
I know this is a bit old question , But It happened that I struggled with this api once , So I hope this may help someone :)

Accessing database on server using android studio

I'm a complete beginner in android programming and am trying to make an app which requires access to the database on local host using the android studio, using the IP address of the server, I've watched many tutorial videos but still am not sure where to pass the IP address of the server.
The server uses MySQL, I've tried using JDBC but still unable to achieve the result.
Here is my code, any help would be appreciated.
`package com.example.vishal.connectiontest;
import java.sql.*;
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 static android.R.attr.name;
import static com.example.vishal.connectiontest.DemoClass.main;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button B1 = (Button)findViewById(R.id.button);
final TextView e1 = (TextView) findViewById(R.id.HelloWorld);
B1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
String result = main();
e1.setText(result.toString());
}
catch(java.lang.Exception e){
System.out.println("Exception");
}
}
});
}
}
class DemoClass
{
public static String main()throws Exception
{
String url = "jdbc:mysql://125.10.10.214/demo" ;
String uname = "root";
String pass = "";
String ip = "";
String query = "Select UserName from user_info where Id = '90000515'";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, uname,pass);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
rs.next();
String name = rs.getString("UserName");
return (name);
}
}`
Easiest way of integrating Database to your Android Application is using Firebase.
It's really easy to use and other than Database, it has File Storage Services, Cloud Messaging, Analytics and many more.
I would recommend use of firebase database.
Here have a look at it's Documentation:
https://firebase.google.com/docs/database/

My Android multi-threaded server does not work properly

I'm trying to set up a score update server on my Android device. Other phones can send scores and this server needs to show the visual results by updating the score of each client. Something like this:
Now my problems are:
1- The current multi-thread approach does not work. What is wrong with it?
2- How can I differentiate people when I receive them? Maybe by having a key-value/hashmap, and update the score corresponding to each IP/socket?
package course.examples.Sensors.ShowValues;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class test extends Activity{
// Start with some variables
int i = 0;
int people = 0;
ArrayList<Bar> diagrams;
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
private static HashMap<String, Integer> map;
boolean isDone=false;
private TextView mXValueView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// set orientation
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
mXValueView = (TextView) findViewById(R.id.textView1);
map= new HashMap<String, Integer>();
diagrams=new ArrayList<Bar>();
// In onCreate method
// diagrams = new ArrayList<Bar>();
// draw(0,0);
// connect_draw();
new Thread(new Runnable() {
public void run() {
connect_draw();
}
}).start();
}
// Register listener
#Override
protected void onResume() {
super.onResume();
}
// Unregister listener
#Override
protected void onPause() {
super.onPause();
}
// void draw() {
// Bar d = new Bar();
// d.setColor(Color.parseColor("#118800"));
// d.setName("Test1");
// d.setValue(i);
// Bar d2 = new Bar();
// d2.setColor(Color.parseColor("#FFBB33"));
// d2.setName("Test2");
// d2.setValue(20);
// diagrams.add(d);
// diagrams.add(d2);
// BarGraph g = (BarGraph) findViewById(R.id.graph);
// g.setBars(diagrams);
// }
void draw(int hash, int score){
//the person was not existed: Create a new Bar
if(!map.containsKey(hash) ){
Bar d = new Bar();
d.setColor(Color.rgb(new Random().nextInt(255), new Random().nextInt(255), new Random().nextInt(255)));
d.setName(people++ +"");
d.setValue((float)score);
diagrams.add(d);
}
BarGraph g = (BarGraph)findViewById(R.id.graph);
g.setBars(diagrams);
}
void connect_draw() {
try {
serverSocket = new ServerSocket(8888); // Server socket
Log.i("hello","hello: Server started. Listening to the port 8888");
isDone=true;
while (true) {
clientSocket = serverSocket.accept(); // accept the client
// connection
inputStreamReader = new InputStreamReader(
clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader); // get the client message
message = bufferedReader.readLine();
final int hash=clientSocket.getInetAddress().hashCode();
// i++;
// draw(hash,Integer.parseInt(message));
mXValueView.setText(message);
Log.i("hello","hello: server received "+message+ " from "+hash);
inputStreamReader.close();
clientSocket.close();
}
}catch (IOException ex) {
Log.e("hello","hello: problem in reading message");
}
}
}
And this is the client code:
package com.lakj.comspace.simpletextclient;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class SlimpleTextClientActivity extends Activity {
private Socket client;
private PrintWriter printwriter;
private EditText textField;
private Button button;
private String messsage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slimple_text_client);
textField = (EditText) findViewById(R.id.editText1); // reference to the text field
button = (Button) findViewById(R.id.button1); // reference to the send button
// Button press event listener
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
messsage = textField.getText().toString(); // get the text message on the text field
textField.setText(""); // Reset the text field to blank
SendMessage sendMessageTask = new SendMessage();
sendMessageTask.execute();
}
});
}
private class SendMessage extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
//10.73.172.214
client = new Socket("10.73.172.214", 8888); // connect to the server
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.write(messsage); // write the message to output stream
printwriter.flush();
printwriter.close();
client.close(); // closing the connection
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.slimple_text_client, menu);
return true;
}
}
UPDATE: I've just added a simple textView, and noticed actually I'm not updating the UI view on another thread. How should I do that? Here is the warning stuff.
06-21 14:44:31.871: E/ACDB-LOADER(257): Error: ACDB audproc returned = -8
06-21 14:44:31.871: E/ACDB-LOADER(257): Error: ACDB AudProc vol returned = -8
06-21 14:44:31.951: W/InputMethodManagerService(575): Starting input on non-focused client com.android.internal.view.IInputMethodClient$Stub$Proxy#41e1aff0 (uid=10043 pid=2841)
06-21 14:44:35.004: E/ALSADevice(257): standby handle h 0x41597050
06-21 14:44:35.054: E/ALSADevice(257): Number of modifiers 0
06-21 14:44:35.054: E/ALSADevice(257): usecase_type is 0
06-21 14:44:35.895: W/ActivityManager(575): No content provider found for permission revoke: file:///data/local/tmp/test.apk
06-21 14:44:35.895: W/ActivityManager(575): No content provider found for permission revoke: file:///data/local/tmp/test.apk
06-21 14:44:36.115: W/PackageManager(575): Code path for pkg : course.examples.Sensors.ShowValues changing from /data/app/course.examples.Sensors.ShowValues-1.apk to /data/app/course.examples.Sensors.ShowValues-2.apk
06-21 14:44:36.115: W/PackageManager(575): Resource path for pkg : course.examples.Sensors.ShowValues changing from /data/app/course.examples.Sensors.ShowValues-1.apk to /data/app/course.examples.Sensors.ShowValues-2.apk
06-21 14:44:36.315: W/ResourceType(575): Failure getting entry for 0x7f060000 (t=5 e=0) in package 0 (error -75)
06-21 14:44:36.315: W/ResourceType(575): Failure getting entry for 0x7f060000 (t=5 e=0) in package 0 (error -75)
06-21 14:44:36.315: W/InputMethodManagerService(575): Found no subtypes in a system IME: com.android.inputmethod.pinyin
06-21 14:44:36.365: W/RecognitionManagerService(575): no available voice recognition services found
06-21 14:44:36.796: W/ProcessStats(575): Skipping unknown process pid 2918
06-21 14:44:36.806: W/ProcessStats(575): Skipping unknown process pid 2923
06-21 14:44:36.806: W/ProcessStats(575): Skipping unknown process pid 2929
06-21 14:44:36.806: W/ProcessStats(575): Skipping unknown process pid 2933
06-21 14:44:37.216: E/Trace(2953): error opening trace file: No such file or directory (2)
06-21 14:44:37.356: E/hello(2953): hello: problem in reading message
06-21 14:44:37.406: E/BufferQueue(254): [Starting course.examples.Sensors.ShowValues] drainQueueLocked: BufferQueue has been abandoned!
06-21 14:44:37.486: W/IInputConnectionWrapper(869): showStatusIcon on inactive InputConnection
06-21 14:44:56.447: W/CNE(575): UNKOWN Unsolicited Event 5
06-21 14:44:59.410: E/StatusBar.NetworkController(662): updateDataNetType NETWORK_TYPE_UNKNOWN
06-21 14:44:59.450: E/StatusBar.NetworkController(662): updateDataNetType NETWORK_TYPE_UNKNOWN
We cannot see what your client send. We see that your server reads one line and then closes the client. The server then increments variable i. The server does nothing with the info in the received line. Every client should place an identifier in that line followed by a score. The server would then decode identifier and score from that line. You are displaying a diagram but it is not yours?

FTPS connection in android

I am new to android, i want to download the files from FTPs server, On emulater i am able to download files but when i try on target board it is giving error at ftp.auth(SSLFTPClient.AUTH_TLS);
Below is the my code, please suggest me where i am wrong.
package com.android.ftp;
import java.io.File;
import android.app.Activity;
import android.os.Bundle;
import com.enterprisedt.net.ftp.FTPClientInterface;
import com.enterprisedt.net.ftp.FTPConnectMode;
import com.enterprisedt.net.ftp.FTPTransferType;
import com.enterprisedt.net.ftp.ssl.SSLFTPClient;
import com.enterprisedt.util.debug.Level;
import com.enterprisedt.util.debug.Logger;
public class Ftp_testActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String host = "ftp.xyz.com";
String username = "abcd";
String password = "pqr";
String filename = "/mnt/sdcard/video1/747.3gp";
// set up logger so that we get some output
Logger log = Logger.getLogger(Ftp_testActivity.class);
Logger.setLevel(Level.INFO);
SSLFTPClient ftp = null;
try {
// create client
log.info("Creating FTPS (explicit) client");
ftp = new SSLFTPClient();
// disable standard SSL closure
log.info("Setting configuration flags");
ftp.setConfigFlags(SSLFTPClient.ConfigFlags.DISABLE_SSL_CLOSURE);
// set remote host
log.info("Setting remote host");
ftp.setRemoteHost(host);
ftp.setRemotePort(21);
// turn off server validation
log.info("Turning off server validation");
ftp.setValidateServer(false);
// connect to the server
log.info("Connecting to server " + host);
ftp.connect();
// switch to SSL on control channel
log.info("Switching to FTPS (explicit mode)");
ftp.auth(SSLFTPClient.AUTH_TLS);
// log in
log.info("Logging in with username=" + username + " and password="
+ password);
ftp.login(username, password);
log.info("Logged in");
ftp.setConnectMode(FTPConnectMode.PASV);
ftp.setType(FTPTransferType.ASCII);
putGetDelete(filename, ftp);
log.info("Successfully transferred in ASCII mode");
// Shut down client
log.info("Quitting client");
ftp.quit();
log.info("Example complete");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void putGetDelete(String name, FTPClientInterface ftp)
throws Exception {
ftp.put(name, name);
ftp.get(name + ".copy", name);
ftp.delete(name);
File file = new File(name + ".copy");
file.delete();
}
}
You should try:
ftp.setRemotePort(990);
where 990 is port SSL default.

Categories

Resources