i tried to upload the image to the server for two days but i could not post the image .the coding is compiled and run sucessfully but the imag is not write into the server.
this is my coding:
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.Toast;
public class sde extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
loadtoUrl("http://
");
}
private void loadtoUrl(String string) {
// TODO Auto-generated method stub
try {
String pathToOurFile = "/sdcard/tamil.PNG";
FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );
BufferedInputStream bis = new BufferedInputStream(fileInputStream,3000);
byte[] bt=new byte[bis.available()];
HttpURLConnection connection = (HttpURLConnection)new URL(string).openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.connect();
FileOutputStream input = (FileOutputStream) connection.getOutputStream();
input.write(bt);
} catch (MalformedURLException e) {
Context context = null;
int duration = 0;
Toast.makeText(context, "erro in writing", duration);
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
here is a nice article, http://blog.sptechnolab.com/2011/03/09/android/android-upload-image-to-server/. It contains an example that will upload an image and write it at server side. It works.
public boolean fileUpload(Map<String , String> params, ByteArrayOutputStream file, String link) throws Throwable{
Account user = Util.getAccount(getApplicationContext());
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(link);
MultipartEntity multipartContent = new MultipartEntity();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String , String> entry : params.entrySet()) {
multipartContent.addPart(entry.getKey(),new StringBody(entry.getValue(),Charset.forName(HTTP.UTF_8)));
}
}
byte[] data = file.toByteArray();
ByteArrayBody img = new ByteArrayBody(data, "capture.jpg");
multipartContent.addPart("image",img);
postRequest.setEntity(multipartContent);
HttpResponse res = httpClient.execute(postRequest);
res.getEntity().getContent().close();
return true;
}catch(Throwable e){
throw e;
}
}
Related
Please suggest the best way to send and receive image files using JSON?
Android: Upload image or file using http POST multi-part
By using multi-part , you will be able to upload a file from your SD Card and also Bitmap image as a file.
Prerequisite: httpmime-4.1-beta1.jar
Android SDK uses apache http Client of version 3.0. That does not support for the mime type.
package com.isummation.fileupload;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
public class FileUpload extends Activity {
Bitmap bm;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
// bm = BitmapFactory.decodeResource(getResources(),
// R.drawable.forest);
bm = BitmapFactory.decodeFile("/sdcard/DCIM/forest.png");
executeMultipartPost();
} catch (Exception e) {
Log.e(e.getClass().getName(), e.getMessage());
}
}
public void executeMultipartPost() throws Exception {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(
"http://10.0.2.2/cfc/iphoneWebservice.cfc?returnformat=json&method=testUpload");
ByteArrayBody bab = new ByteArrayBody(data, "forest.jpg");
// File file= new File("/mnt/sdcard/forest.png");
// FileBody bin = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("uploaded", bab);
reqEntity.addPart("photoCaption", new StringBody("sfsdfsdf"));
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
System.out.println("Response: " + s);
} catch (Exception e) {
// handle exception here
Log.e(e.getClass().getName(), e.getMessage());
}
}
}
See below link:
Multipart Image Upload
I am currently populating a RrecyclerView from a remote database but wish to only query the database for dates based on a users ID. I have the userID assigned as a global variable on the LoginActivty of the app but I'm not sure where to pass that information to the php page from my DateActivity.
My Code for the DateActivity is as follows:
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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;
import java.util.ArrayList;
import java.util.List;
public class DateActivity extends AppCompatActivity {
public static String globex_num;
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVDateList;
private AdapterDate mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_date);
//Make call to AsyncTask
new AsyncFetch().execute();
}
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(DateActivity.this);
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
url = new URL("thephpfile.com");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
List<DataDate> data=new ArrayList<>();
pdLoading.dismiss();
try {
JSONArray jsonArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for(int i=0;i<jsonArray.length();i++){
JSONObject json_data = jsonArray.getJSONObject(i);
DataDate dateData = new DataDate();
dateData.date= json_data.getString("date");
data.add(dateData);
}
// Setup and Handover data to recyclerview
mRVDateList = (RecyclerView)findViewById(R.id.dateList);
mAdapter = new AdapterDate(DateActivity.this, data);
mRVDateList.setAdapter(mAdapter);
mRVDateList.setLayoutManager(new LinearLayoutManager(DateActivity.this));
} catch (JSONException e) {
Toast.makeText(DateActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
I solved the problem by passing it though the link.
url = new URL(www.thephpfile.php?userID=" + LoginActivity.userID);
At the start of the php file I did the following:
$userID = $_GET['userID'];
I'm trying to connect server socket using android. Please check the code below. I'm trying to send data from android to server as well as send data back to android from server but it is causing timeout exception at android side.
package com.example.orderdish;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MenuActivity extends Activity {
Button vegButton, nonVegButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
vegButton = (Button) findViewById(R.id.btn_veg);
nonVegButton = (Button) findViewById(R.id.btn_non_veg);
}
public void openCategory(View view) {
Button button = (Button)view;
Toast.makeText(getApplicationContext(), button.getText().toString() + " selected", Toast.LENGTH_LONG).show();
//Intent intent = new Intent(getApplicationContext(), ListCategoryActivity.class);
//startActivity(intent);
MyClientTask myClientTask = new MyClientTask(
"my ip",
1234);
myClientTask.execute();
}
public class MyClientTask extends AsyncTask<Void, Void, String> {
String dstAddress;
int dstPort;
String response = "";
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
MyClientTask(String addr, int port){
dstAddress = addr;
dstPort = port;
}
#Override
protected String doInBackground(Void... arg0) {
Socket socket = null;
try {
Timer timer = new Timer(3000);
timer.start();
//Connect to remote host
socket = new Socket(dstAddress, dstPort);
Log.v("MenuActivity: ", "Connected to 1234 port");
//Reset timer - timeout can occur on connect
// InputStream inputStream = socket.getInputStream();
//create data output stream for writing
PrintStream pout = new PrintStream(socket.getOutputStream());
//dataOutputStream = new DataOutputStream(socket.getOutputStream());
// dataOutputStream.writeUTF("v");
//create data input stream for reading
DataInputStream din = new DataInputStream(socket.getInputStream());
//Print hello message
pout.println("Hello world");
//Reset timer - timeout is likely to occur during the read
timer.reset();
//print message from server
// dataInputStream = new DataInputStream(socket.getInputStream());
// response = dataInputStream.readUTF();
// Log.v("MenuActivity", "hi.." + dataInputStream.readUTF());
ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
/*
* notice:
* inputStream.read() will block if no data return
*/
while ((bytesRead = din.read(buffer)) != -1){
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
Log.v("MenuActivity ", response);
timer.stop();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}finally{
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
// textResponse.setText(response);
Log.v("MenuActivity", result);
super.onPostExecute(result);
}
}
}
package com.orderdish.main;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import com.google.gson.Gson;
public class Test {
// List<Menu> menuList;
public static void main(String args[]) {
ServerSocket serverSocket = null;
Socket socket = null;
String str;
List<Menu> menuList;
try {
serverSocket = new ServerSocket(1234);
socket = serverSocket.accept();
System.out.println("Server has connected!\n");
socket.setSoTimeout(100000);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while ((str = br.readLine()) != null) {
System.out.println("The message: " + str.trim());
}
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
System.out.println("Sending string ... sample data\n");
out.println("sample data");
out.close();
br.close();
socket.close();
serverSocket.close();
} catch(Exception e) {
System.out.println("Whoops! It didn't work!\n : " + e.getMessage().toString());
}
}
}
**Please find the modified code**
package com.example.orderdish;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import org.json.JSONArray;
import org.json.JSONException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MenuActivity extends Activity {
int current = 0;
Context ctx;
Button vegButton, nonVegButton;
String ip = "XXX.XXX.X.XX"; //Server IP
int portNo = 1234; //Port no.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
ctx = getApplicationContext();
vegButton = (Button) findViewById(R.id.btn_veg);
nonVegButton = (Button) findViewById(R.id.btn_non_veg);
vegButton.setOnClickListener(buttonConnectOnClickListener);
nonVegButton.setOnClickListener(buttonConnectOnClickListener);
}
OnClickListener buttonConnectOnClickListener =
new OnClickListener(){
#Override
public void onClick(View view) {
MyClientTask myClientTask = new MyClientTask(
ip, portNo);
myClientTask.execute();
}};
public class MyClientTask extends AsyncTask<Void, Void, String> {
String dstAddress;
int dstPort;
String menuType;
String response = "";
String received_message;
MyClientTask(String addr, int port){
dstAddress = addr; //server ip
dstPort = port; //server port
}
#Override
protected String doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
DataOutputStream pout = new DataOutputStream(socket.getOutputStream());
pout.writeUTF(menuType);
DataInputStream dis = new DataInputStream(socket.getInputStream());
received_message = DataInputStream.readUTF(dis);
pout.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
} finally{
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return received_message;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
}
package com.orderdish.main;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
public class Test {
public final static int SOCKET_PORT = 1234;
public static DataInputStream dis;
public static DataOutputStream dos;
public static void main(String args[]) throws IOException {
ServerSocket serverSocket = null;
Socket socket = null;
try {
serverSocket = new ServerSocket(SOCKET_PORT);
while(true) {
System.out.println("Waiting...");
try {
socket = serverSocket.accept();
System.out.println("Accepted connection: " + socket);
//Here is the change
dis = new DataInputStream(socket.getInputStream());
String received_message = DataInputStream.readUTF(dis);
dos = new DataOutputStream(socket.getOutputStream());
dos.writeUTF("sample data");
} catch(Exception e) {
System.out.println("Whoops! It didn't work!\n");
} finally {
if(dis != null) dis.close();
if(dos != null) dos.close();
if(socket != null)
socket.close();
}
}
} finally {
if(serverSocket != null) serverSocket.close();
}
}
}
I am making a simple browser for school and I am trying to make the favorites. This code here adds a favorite to a file(so I can keep it after the app is closed) and displays it in the TextView. My problem is that it can only save one. If i add the second one, the first one is replaced. I thought i could add them in an array or arrayList(or anything that works, i am open to suggestions), but i can't succeed. Thanks for the help.
package com.example.browser3;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Favorite extends Activity {
EditText etName;
EditText etAdress;
Button bAdd;
TextView tvDisplay;
protected void onResume() {
readFile("favorite.txt", tvDisplay);
super.onResume();
}
public void writeFile(String fileName, EditText v, EditText x){
try {
OutputStreamWriter out=new OutputStreamWriter(openFileOutput(fileName,0));
out.write(v.getText().toString()+ x.getText().toString());
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void readFile(String fileName, TextView w){
try {
InputStream in=openFileInput(fileName);
if(in!=null){
InputStreamReader reader= new InputStreamReader(in);
BufferedReader buffreader= new BufferedReader(reader);
StringBuilder builder= new StringBuilder();
String str;
while((str=buffreader.readLine())!=null){
builder.append(str+ "\n");
}
in.close();
w.setText(builder.toString());
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favorite);
etName = (EditText) findViewById(R.id.etName);
etAdress = (EditText) findViewById(R.id.etAdress);
bAdd = (Button) findViewById(R.id.bAdd);
tvDisplay = (TextView) findViewById(R.id.tvDisplay);
bAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
writeFile("favorite.txt",etName, etAdress);
readFile("favorite.txt", tvDisplay);
}
});
}
}
to write at first position i.e. prepend then u need to use this
private void writeToFile(Context context,String data){
try{
String path=context.getFilesDir().getAbsolutePath();
File file = new File(path + File.separator + fileName);
RandomAccessFile rf = new RandomAccessFile(file,"rws");
file.getParentFile().mkdirs();
Log.d("creating file path",path);
byte[] text = new byte[(int) file.length()];
rf.readFully(text);
rf.seek(0);
rf.writeBytes(data);
rf.write(text);
Log.d("write","writing file...");
rf.close();
}catch(Exception e){e.printStackTrace(); Log.d("caught", "data wititng fail");}
}
and if u want to append use this
private void writeToFile(Context context,String data){
try{
String path=context.getFilesDir().getAbsolutePath();
File file = new File(path + File.separator + fileName);
RandomAccessFile rf = new RandomAccessFile(file,"rws");
file.getParentFile().mkdirs();
Log.d("creating file path",path);
byte[] text = new byte[(int) file.length()];
rf.readFully(text);
rf.seek(0);
rf.write(text);
rf.writeBytes(data);
Log.d("write","writing file...");
rf.close();
}catch(Exception e){e.printStackTrace(); Log.d("caught", "data wititng fail");}
}
or u can open file in MODE_APPEND mode.. to open file in append mode change to this OutputStreamWriter out=new OutputStreamWriter(openFileOutput(fileName,true));
I'm trying to make a login interface in android , i want to connect to a php file that connects to a database.
the database is called "daymanager" and the table is "login"
And this is the php file called login.php :
<?php
$host="localhost";
$user="root";
$pass="";
$dbname="daymanager";
$con= mysql_connect($host,$user,$pass);
$BD= mysql_select_db($dbname, $con);
//$username=$_POST['username'];
//$password=$_POST['password'];
$query=mysql_query("select username,password from login");
$num=mysql_num_rows($query);
if($num==1)
{
while($list=mysql_fetch_array($query))
{
$output=$row[username];
echo json_encode($output);
}
mysql_close();
}
?>
and this is the java code in eclipse :
package com.mounzer.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.HostNameResolver;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Activating extends Activity implements OnClickListener {
Button login;
EditText user,pass;
String username,password;
HttpClient httpclient;
HttpPost httppost;
ArrayList<NameValuePair> namevaluepairs;
HttpResponse response;
HttpEntity entity;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activ);
initialise();
}
private void initialise() {
// TODO Auto-generated method stub
login =(Button) findViewById(R.id.login);
user=(EditText) findViewById(R.id.user);
pass=(EditText) findViewById(R.id.pass);
login.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
httpclient = new DefaultHttpClient();
httppost =new HttpPost("http://192.168.48.1:6789/aglprojet/Login.php");
username=user.getText().toString();
password=pass.getText().toString();
try
{
namevaluepairs = new ArrayList<NameValuePair>();
namevaluepairs.add(new BasicNameValuePair("username", username));
namevaluepairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(namevaluepairs));
response=httpclient.execute(httppost);
if(response.getStatusLine().getStatusCode()==200)
{
entity=response.getEntity();
if(entity !=null)
{
InputStream instream=entity.getContent();
JSONObject jsonResponse=new JSONObject(convertStreamToString(instream));
String retUser = jsonResponse.getString("username");
String retPass = jsonResponse.getString("password");
if(username.equals(retUser) && password.equals(retPass))
{
SharedPreferences sp=getSharedPreferences("logindetails", 0);
SharedPreferences.Editor spedit=sp.edit();
spedit.putString("user",username);
spedit.putString("pass",password);
spedit.commit();
Toast.makeText(getBaseContext(),"Succesfully connected", Toast.LENGTH_SHORT).show();
}else {Toast.makeText(getBaseContext(),"Invalid username or password", Toast.LENGTH_SHORT).show(); }
}
}
}catch(Exception e)
{
e.printStackTrace();
Toast.makeText(getBaseContext(),e.toString(), Toast.LENGTH_LONG).show();
}
}
private void Log(String string, String retUser) {
// TODO Auto-generated method stub
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(null, e.toString(), Toast.LENGTH_SHORT).show();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(null, e.toString(), Toast.LENGTH_SHORT).show();
}
}
return sb.toString();
}
}
when I try the application from my mobile , it gives me this exception :
org.json.JSONException : value <html> of type java.lang.string cannot be converted to JSONObject
can anyone tell me what should I do please
thank you
My guess is that something is running into an error and returning an error message wrapped in HTML. Try calling your authentication script via a browser or anything that lets you see what it actually returns.
Also, you don't seem to return any fields in your output, so getString("username") etc is never going to work. If you want to return multiple things from your authentication script, put them into an array or something and json_encode that.
And finally, are you sure it's a good idea to send the password to your client...? (I'm guessing you're trying to do this judging by the fact that you try to read them back from the response)