Category Archives: android-asynctask

Apache Poi 64K Error in Espresso Test

I have a problem in Espresso. I must compare a text with an excel cell. Studio says the following when I call apache poi methods.

Error:The number of method references in a .dex file cannot exceed 64K.

I've tried this in my other project and it works well. I've tried to enable multiDex but it gives some other errors because we are using async http master to get movies,music and other content I can't change main project files. There are so much methods, classes and layouts.

Consequently my Question is: is There any way to solve .dex file cannot exceed 64K Error.

send string to esp8266 via android using telnet

Im trying to send a string to ESP8266.I want to send it through Android App and see the result in serial monitor of Arduino environment.

1 Im not able to connect to the server.

2 Also, Im getting nullPointerException as Attempt to invoke virtual method .

Heres the error Im unable to resolve in Android code:- I/OpenGLRenderer: Initialized EGL, version 1.4 D/OpenGLRenderer: Get maximum texture size. GL_MAX_TEXTURE_SIZE is 4096 enter code hereD/OpenGLRenderer: Enabling debug mode 0 I/Timeline: Timeline: Activity_idle id: [email protected] time:898904480 D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN E/PioneerController: Could not establish connection with server W/System.err: java.net.SocketException: Connection error... W/System.err: at com.example.manveenkaur.optimized.TelnetConnection.connect(TelnetConnection.java:29) W/System.err: at com.example.manveenkaur.optimized.TelnetClient.<init>(TelnetClient.java:27) W/System.err: at com.example.manveenkaur.optimized.PioneerController.<init>(PioneerController.java:24) W/System.err: at com.example.manveenkaur.optimized.MainActivity$1.doInBackground(MainActivity.java:82) W/System.err: at com.example.manveenkaur.optimized.MainActivity$1.doInBackground(MainActivity.java:78) W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:292) W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237) W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) W/System.err: at java.lang.Thread.run(Thread.java:818) E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #3 Process: com.example.manveenkaur.optimized, PID: 31509 java.lang.RuntimeException: An error occured while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:304) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) at java.util.concurrent.FutureTask.setException(FutureTask.java:222) at java.util.concurrent.FutureTask.run(FutureTask.java:242) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:818) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.InputStreamReader com.example.manveenkaur.optimized.TelnetClient.spawnSpy()' on a null object reference at com.example.manveenkaur.optimized.PioneerController.<init>(PioneerController.java:34) at com.example.manveenkaur.optimized.MainActivity$1.doInBackground(MainActivity.java:82) at com.example.manveenkaur.optimized.MainActivity$1.doInBackground(MainActivity.java:78) at android.os.AsyncTask$2.call(AsyncTask.java:292) at java.util.concurrent.FutureTask.run(FutureTask.java:237) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)  at java.lang.Thread.run(Thread.java:818)  D/OpenGLRenderer: endAllStagingAnimators on 0xb84bb1f8 (RippleDrawable) with handle 0xb84b3950 I/Process: Sending signal. PID: 31509 SIG: 9 Application terminated. Here is the App code
MainActivity.java

public class MainActivity extends AppCompatActivity {
EditText editText_message;
Button button_send, button_connect, button_disconnect;
private Toast fastToast;
private static String SERVER_IP = "192.168.4.1";
private static int SERVERPORT = 1155;
private PioneerController clientPioneerController = null;
@SuppressLint("ShowToast")

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    editText_message = (EditText) findViewById(R.id.EditTextMessage);
    button_send = (Button) findViewById(R.id.sendButton);
    button_connect = (Button) findViewById(R.id.connectButton);
    button_disconnect = (Button) findViewById(R.id.disconnectButton);
}

public void onClickSend(View view) {
    if (clientPioneerController == null || !clientPioneerController.isConnected()) {
        toastFast("Not connected to a server");
        return;
    }


    clientPioneerController.sendCommand(editText_message.getText().toString());

}


void toastFast(String str) {

    fastToast.setText(str);
    fastToast.show();
}

public void onClickDisconnect(View view){
    if (clientPioneerController!=null && clientPioneerController.isConnected()) {
        if(disconnect()){
            toastFast("Disconnected from server");
        }
        else toastFast("Error disconnecting from server");
    }
    else{
        toastFast("Already disconnected");
    }
}
private boolean disconnect(){
    if(clientPioneerController.disconnect()){
        return true;
    }
    return false;
}

public void onClickConnect(View view){

    if(clientPioneerController!=null && clientPioneerController.isConnected())
        toastFast("Already connected");
    else {
        try{
            new AsyncTask<MainActivity, Void, Void>() {
                @Override
                protected Void doInBackground(MainActivity... act) {
                    try {
                        clientPioneerController = new PioneerController(SERVER_IP, SERVERPORT, act[0]);
                    } catch (IOException | InterruptedException e) {
                        e.printStackTrace();
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(Void aVoid) {
                    toastFast("Hogya connect");

                }
            }.execute(this);
        }catch (Exception ex){
            ex.printStackTrace();
        }

    }
}
public void appendToConsole(String str){
    editText_message.append("\n");
    editText_message.append(str);
}
}

PioneerController.java

public class PioneerController {

private TelnetClient clientTelnetClient;
private MainActivity context;
protected static final String TAG = "PioneerController";


public PioneerController(String ip, int port, MainActivity con) throws     IOException, InterruptedException {
    TelnetClient connection = null;
    try {
        connection = new TelnetClient(ip, port);
    } catch (IOException e) {
        Log.e(TAG, "Could not establish connection with server");
        e.printStackTrace();
    }
    clientTelnetClient = connection;
    context = con;
    final InputStreamReader a = clientTelnetClient.spawnSpy();
    final BufferedReader reader = new BufferedReader(a);
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                while (!Thread.currentThread().isInterrupted()) {
                    final String line = reader.readLine();
                    if (line != null) {
                        context.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                context.appendToConsole(line);
                            }
                        });
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();
}

public boolean isConnected() {
    return clientTelnetClient.isConnected();
}

public boolean disconnect() {
    return clientTelnetClient.disconnect();
}

public void sendCommand(String s) {
    clientTelnetClient.sendCommand(s);
}
}

TelnetClient.java

public class TelnetClient {
private TelnetConnection clientTelnetConnection;
private OutputStream outstream;
private org.apache.commons.net.telnet.TelnetClient rawConnection;
private InputStream instream;
private PipedInputStream spyReader;


public TelnetClient(String ip, int port) throws IOException {
    clientTelnetConnection = new TelnetConnection(ip, port);
    clientTelnetConnection.connect();
    rawConnection = clientTelnetConnection.getConnection();
    outstream = clientTelnetConnection.getOutput();
    instream = clientTelnetConnection.getReader();
}

public InputStreamReader spawnSpy() throws InterruptedException, IOException {
    PipedInputStream in = new PipedInputStream();
    PipedOutputStream out = new PipedOutputStream();
    in.connect(out);
    if (spyReader != null) {
        return spawnSpy(spyReader, out);
    } else {
        spyReader = in;
        return spawnSpy(instream, out);
    }
}

private InputStreamReader spawnSpy(InputStream in, PipedOutputStream   pipeout) throws InterruptedException {
    return new InputStreamReader(new TeeInputStream(in, pipeout));
}

public boolean isConnected() {
    return clientTelnetConnection.isConnected();
}

public boolean disconnect() {
    spyReader = null;
    return clientTelnetConnection.disconnect();
}

public boolean sendCommand(String cmd) {
    if (clientTelnetConnection == null || !clientTelnetConnection.isConnected()) {
        return false;
    }
    StringBuilder stringBuilder = new StringBuilder();

    stringBuilder.append(cmd.toUpperCase(Locale.ENGLISH));
    stringBuilder.append("\n\r");

    byte[] cmdbyte = stringBuilder.toString().getBytes();

    try {
        outstream.write(cmdbyte, 0, cmdbyte.length);
        outstream.flush();
        return true;
    } catch (Exception e1) {
        return false;
    }
}
}

TelnetConnection.java

public class TelnetConnection {
private TelnetClient client = null;
private final String SERVER_IP;
private final int SERVERPORT;

public TelnetConnection(String ip, int port) throws IOException {
    SERVER_IP = ip;
    SERVERPORT = port;
    client = new TelnetClient();
}

public void connect() throws IOException {
    try {
        client.connect(SERVER_IP, SERVERPORT);
    } catch (SocketException ex) {
        throw new SocketException("Connection error...");
    }
}

public TelnetClient getConnection() {
    return client;
}

public OutputStream getOutput() {
    return client.getOutputStream();
}

public BufferedInputStream getReader() {
    return new BufferedInputStream(client.getInputStream());
}

public boolean isConnected() {
    return client.isConnected();
}

public boolean disconnect() {
    try {
        client.disconnect();
    } catch (IOException e) {
        Log.e("Couldn't disconnect", e.getMessage());
        return false;
    }
    return true;
}


}

Error in running httpget request on AsyncTask

I tried running the block of code in the getInfo method in a separate program and it ran without error. Earlier the issue appeared to be a connection error but after fixing that these errors appeared.

I want the code to query localhost/getUser.php and save the resultant JSON object in User.java in response to a click event.

04-07 09:36:55.641: E/AndroidRuntime(3724): FATAL EXCEPTION: AsyncTask #1
04-07 09:36:55.641: E/AndroidRuntime(3724): Process: com.example.meetup,PID: 3724
04-07 09:36:55.641: E/AndroidRuntime(3724): java.lang.RuntimeException: An error occured while executing doInBackground()
04-07 09:36:55.641: E/AndroidRuntime(3724):     at android.os.AsyncTask$3.done(AsyncTask.java:300)
04-07 09:36:55.641: E/AndroidRuntime(3724):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
04-07 09:36:55.641: E/AndroidRuntime(3724):     at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
04-07 09:36:55.641: E/AndroidRuntime(3724):     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
04-07 09:36:55.641: E/AndroidRuntime(3724):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
04-07 09:36:55.641: E/AndroidRuntime(3724):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
04-07 09:36:55.641: E/AndroidRuntime(3724):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
04-07 09:36:55.641: E/AndroidRuntime(3724):     at java.lang.Thread.run(Thread.java:818)
04-07 09:36:55.641: E/AndroidRuntime(3724): Caused by: java.lang.IllegalArgumentException: Host name may not be null
04-07 09:36:55.641: E/AndroidRuntime(3724):     at org.apache.http.HttpHost.<init>(HttpHost.java:83)
04-07 09:36:55.641: E/AndroidRuntime(3724):     at org.apache.http.impl.client.AbstractHttpClient.determineTarget(AbstractHttpClient.java:497)
04-07 09:36:55.641: E/AndroidRuntime(3724):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
04-07 09:36:55.641: E/AndroidRuntime(3724):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
04-07 09:36:55.641: E/AndroidRuntime(3724):     at com.example.meetup.User.getInfo(User.java:53)
04-07 09:36:55.641: E/AndroidRuntime(3724):     at com.example.meetup.User.createStudent(User.java:36)
04-07 09:36:55.641: E/AndroidRuntime(3724):     at com.example.meetup.MainActivity$HttpTask.doInBackground(MainActivity.java:39)
04-07 09:36:55.641: E/AndroidRuntime(3724):     at com.example.meetup.MainActivity$HttpTask.doInBackground(MainActivity.java:1)
04-07 09:36:55.641: E/AndroidRuntime(3724):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
04-07 09:36:55.641: E/AndroidRuntime(3724):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
04-07 09:36:55.641: E/AndroidRuntime(3724):     ... 4 more

The MainActivity.java file

package com.example.meetup;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends Activity {

private EditText userField, passField;
private User user;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    user = new User();
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    userField = (EditText)findViewById(R.id.editText1);
    passField = (EditText)findViewById(R.id.editText2);
}

protected void onStart()
{
    super.onStart();
    Log.i("Progress", "You made it to onStart");
}

public void signIn(View v)
{
    Log.i("Progress", "You made it to signIn");
    new HttpTask().execute();
}
private class HttpTask extends AsyncTask<Void,Boolean,Boolean>{
    @Override
    protected Boolean doInBackground(Void... params) {
        return  user.createStudent(userField.getText().toString(), passField.getText().toString()); 
    }
    protected void onPostExecute(Boolean result) {
        Log.i("result",user.getName());
   }
}
}

The User.java file

package com.example.meetup;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.net.Uri;
import android.util.Log;


public class User
{
    static final String ID = "Id";
    static final String USER = "Username";
    static final String PASS = "Password";
    static final String NAME = "Name";

private boolean userCreated;
private JSONObject User;

public User()
{
    userCreated = false;
    User = new JSONObject();
}

public boolean createStudent(String username, String password)
{
    userCreated = getInfo(username, password);
    return userCreated;
}

private boolean getInfo(String username, String password)
{
    HttpResponse response;
    Log.i("Progress", "You made it to getInfo");
    try {        
        HttpClient client = new DefaultHttpClient();
        Uri uri = Uri.parse("localhost:8080/getUser.php")
                .buildUpon()
                .appendQueryParameter("username", username)
                .appendQueryParameter("password", password)
                .build();
        Log.i("Uri is", uri.toString());
        HttpGet request = new HttpGet(uri.toString());
        response = client.execute(request);
        User = new JSONObject(new BasicResponseHandler().handleResponse(response));
    }
    catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        Log.e("Network error",e.toString());
        return false;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        Log.e("Network error",e.toString());
        return false;
    } catch (JSONException e){
        Log.e("Network error",e.toString());
        return false;
    }
    return true;
}

public int getId()
{
    if(userCreated)
    {
        try {
            return User.getInt(ID);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return -1;
}

public String getName()
{
    if(userCreated)
    {
        try {
            return User.getString(NAME);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return null;
}

public String getUser()
{
    if(userCreated)
    {
        try {
            return User.getString(USER);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return null;
}
}

org.apache.http.client.ClientProtocolException : Authentication challenge is empty

I was trying to authenticate through login activity in android using Base64 authentication in which username and password is sent to web-service after being converted to Base64 and the format to sent username and password is as follows username:password

the problem is that when the username and password is correct it is giving the json in return successfully but when the username or password is wrong it is throwing exception

org.apache.http.client.ClientProtocolException with Caused by: org.apache.http.auth.MalformedChallengeException: Authentication challenge is empty

Here are my codes :

String credentials = values.get(0) + ":" + values.get(1);

String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP|Base64.URL_SAFE);

httpGet = new HttpGet(request.getUrl());

httpGet.setHeader("Authorization", " Basic "+base64EncodedCredentials);

httpGet.setHeader(HTTP.CONTENT_TYPE, "application/json");

HttpResponse httpResponse = client.execute(httpGet);

ERROR I GOT IS:

02-05 15:01:25.168 21466-21504/com.agbe.gosellit E/com.agbe.gosellit.application.WebHandler: null

02-05 15:01:25.168 21466-21504/com.agbe.gosellit E/com.agbe.gosellit.application.WebHandler:org.apache.http.client.ClientProtocolException

02-05 15:01:25.168 21466-21504/com.agbe.gosellit E/com.agbe.gosellit.application.WebHandler: at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:562)

02-05 15:01:25.168 21466-21504/com.agbe.gosellit E/com.agbe.gosellit.application.WebHandler: at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:492)

02-05 15:01:25.168 21466-21504/com.agbe.gosellit E/com.agbe.gosellit.application.WebHandler: at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:470)

02-05 15:01:25.168 21466-21504/com.agbe.gosellit E/com.agbe.gosellit.application.WebHandler: at com.agbe.gosellit.application.WebHandler.doInBackground(WebHandler.java:145)

02-05 15:01:25.168 21466-21504/com.agbe.gosellit E/com.agbe.gosellit.application.WebHandler: at com.agbe.gosellit.application.WebHandler.doInBackground(WebHandler.java:57)

02-05 15:01:25.168 21466-21504/com.agbe.gosellit E/com.agbe.gosellit.application.WebHandler: at android.os.AsyncTask$2.call(AsyncTask.java:292)

02-05 15:01:25.168 21466-21504/com.agbe.gosellit E/com.agbe.gosellit.application.WebHandler: at java.util.concurrent.FutureTask.run(FutureTask.java:237)

02-05 15:01:25.168 21466-21504/com.agbe.gosellit E/com.agbe.gosellit.application.WebHandler: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)

02-05 15:01:25.168 21466-21504/com.agbe.gosellit E/com.agbe.gosellit.application.WebHandler: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)

02-05 15:01:25.168 21466-21504/com.agbe.gosellit E/com.agbe.gosellit.application.WebHandler: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)

02-05 15:01:25.168 21466-21504/com.agbe.gosellit E/com.agbe.gosellit.application.WebHandler: at java.lang.Thread.run(Thread.java:818)

02-05 15:01:25.168 21466-21504/com.agbe.gosellit E/com.agbe.gosellit.application.WebHandler: Caused by: org.apache.http.auth.MalformedChallengeException: Authentication challenge is empty

02-05 15:01:25.168 21466-21504/com.agbe.gosellit E/com.agbe.gosellit.application.WebHandler:at org.apache.http.impl.auth.RFC2617Scheme.parseChallenge(RFC2617Scheme.java:77)

02-05 15:01:25.168 21466-21504/com.agbe.gosellit E/com.agbe.gosellit.application.WebHandler:at org.apache.http.impl.auth.AuthSchemeBase.processChallenge(AuthSchemeBase.java:116)

02-05 15:01:25.168 21466-21504/com.agbe.gosellit E/com.agbe.gosellit.application.WebHandler:at org.apache.http.impl.auth.BasicScheme.processChallenge(BasicScheme.java:100)

02-05 15:01:25.168 21466-21504/com.agbe.gosellit E/com.agbe.gosellit.application.WebHandler:at org.apache.http.impl.client.DefaultRequestDirector.processChallenges(DefaultRequestDirector.java:1073)

02-05 15:01:25.168 21466-21504/com.agbe.gosellit E/com.agbe.gosellit.application.WebHandler:at org.apache.http.impl.client.DefaultRequestDirector.handleResponse(DefaultRequestDirector.java:970)

02-05 15:01:25.168 21466-21504/com.agbe.gosellit E/com.agbe.gosellit.application.WebHandler: at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:480)

02-05 15:01:25.168 21466-21504/com.agbe.gosellit E/com.agbe.gosellit.application.WebHandler: at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:560)

02-05 15:01:25.168 21466-21504/com.agbe.gosellit E/com.agbe.gosellit.application.WebHandler: at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:492) 

02-05 15:01:25.168 21466-21504/com.agbe.gosellit E/com.agbe.gosellit.application.WebHandler: at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:470) 

02-05 15:01:25.168 21466-21504/com.agbe.gosellit E/com.agbe.gosellit.application.WebHandler: at com.agbe.gosellit.application.WebHandler.doInBackground(WebHandler.java:145) 

02-05 15:01:25.168 21466-21504/com.agbe.gosellit E/com.agbe.gosellit.application.WebHandler: at com.agbe.gosellit.application.WebHandler.doInBackground(WebHandler.java:57) 

02-05 15:01:25.168 21466-21504/com.agbe.gosellit E/com.agbe.gosellit.application.WebHandler: at android.os.AsyncTask$2.call(AsyncTask.java:292) 

02-05 15:01:25.168 21466-21504/com.agbe.gosellit E/com.agbe.gosellit.application.WebHandler: at java.util.concurrent.FutureTask.run(FutureTask.java:237) 

02-05 15:01:25.168 21466-21504/com.agbe.gosellit E/com.agbe.gosellit.application.WebHandler: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 

02-05 15:01:25.168 21466-21504/com.agbe.gosellit E/com.agbe.gosellit.application.WebHandler: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 

02-05 15:01:25.168 21466-21504/com.agbe.gosellit E/com.agbe.gosellit.application.WebHandler: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 

02-05 15:01:25.168 21466-21504/com.agbe.gosellit E/com.agbe.gosellit.application.WebHandler: at java.lang.Thread.run(Thread.java:818) 

app going into infinite loop in async task and never comes out

The app receives data from the login page (username and password) The aim is to then post it and then retrieve a result and exit the async task! I should have that! Can anyone spot what I am missing?

here's my page with server requests where the asynchronous

package net.azurewebsites.cosy;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

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.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.util.ArrayList;


public class ServerRequests
{
    ProgressDialog progressDialog;
    public static final int CONNECTION_TIMEOUT = 1000 * 15;
    public static final String SERVER_ADDRESS = "http://cosy.azurewebsites.net/";

    public ServerRequests(Context context)
    {
        progressDialog = new ProgressDialog(context);
        progressDialog.setCancelable(false);
        progressDialog.setTitle("Processing...");
        progressDialog.setMessage("Please wait...");
    }


    public void fetchUserDataAsyncTask(User user, GetUserCallback userCallBack)
    {
        progressDialog.show();
        new fetchUserDataAsyncTask(user, userCallBack).execute();

    }

    public class fetchUserDataAsyncTask extends AsyncTask<Void,Void,User>
    {
        User user;
        GetUserCallback userCallback;

        public fetchUserDataAsyncTask(User user, GetUserCallback userCallback)
        {
            this.user = user;
            this.userCallback = userCallback;

        }

        @Override
        protected User doInBackground(Void... params)
        {
            ArrayList<NameValuePair> dataToSend = new ArrayList();
            dataToSend.add(new BasicNameValuePair("username", user.username));
            dataToSend.add(new BasicNameValuePair("password", user.password));

            HttpParams httpRequestParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
            HttpConnectionParams.setSoTimeout(httpRequestParams,CONNECTION_TIMEOUT);

            HttpClient client = new DefaultHttpClient(httpRequestParams);
            HttpPost post = new HttpPost(SERVER_ADDRESS + "FetchUserData.php");

            User returnedUser= null;

            try
            {
                post.setEntity(new UrlEncodedFormEntity(dataToSend));
                HttpResponse httpResponse = client.execute(post);

                HttpEntity entity = httpResponse.getEntity();
                String result = EntityUtils.toString(entity);
                JSONObject jsonObject = new JSONObject(result);

                if(jsonObject.length()==0)
                {
                    returnedUser=null;

                }

                else
                {
                    returnedUser = new User(user.username, user.password);

                }


            }
            catch (Exception e)
            {
                e.printStackTrace();
            }

            return returnedUser;
        }

        protected void OnPostExecute(User returnedUser)
        {
            progressDialog.dismiss();
            userCallback.done(returnedUser);
            super.onPostExecute(user);

        }
    }



}

here's what happens in the logcat when the task is running:

01-25 07:43:11.013    4194-4312/net.azurewebsites.cosy W/System.err﹕ org.json.JSONException: Value The of type java.lang.String cannot be converted to JSONObject
01-25 07:43:11.173    4194-4312/net.azurewebsites.cosy W/System.err﹕ at org.json.JSON.typeMismatch(JSON.java:111)
01-25 07:43:11.173    4194-4312/net.azurewebsites.cosy W/System.err﹕ at org.json.JSONObject.<init>(JSONObject.java:159)
01-25 07:43:11.183    4194-4312/net.azurewebsites.cosy W/System.err﹕ at org.json.JSONObject.<init>(JSONObject.java:172)
01-25 07:43:11.183    4194-4312/net.azurewebsites.cosy W/System.err﹕ at net.azurewebsites.cosy.ServerRequests$fetchUserDataAsyncTask.doInBackground(ServerRequests.java:83)
01-25 07:43:11.283    4194-4312/net.azurewebsites.cosy W/System.err﹕ at net.azurewebsites.cosy.ServerRequests$fetchUserDataAsyncTask.doInBackground(ServerRequests.java:47)
01-25 07:43:11.283    4194-4312/net.azurewebsites.cosy W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:288)
01-25 07:43:11.393    4194-4312/net.azurewebsites.cosy W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:237)
01-25 07:43:11.393    4194-4312/net.azurewebsites.cosy W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
01-25 07:43:11.453    4194-4312/net.azurewebsites.cosy W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
01-25 07:43:11.523    4194-4312/net.azurewebsites.cosy W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
01-25 07:43:11.643    4194-4312/net.azurewebsites.cosy W/System.err﹕ at java.lang.Thread.run(Thread.java:841)

here's where I call the task from the login:

  protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    etUsername = (EditText) findViewById(R.id.etUsername);
    etPassword = (EditText) findViewById(R.id.etPassword);

    bLogin = (Button) findViewById(R.id.bLogin);

    bLogin.setOnClickListener(this);

}

@Override
public void onClick(View v)
{
    switch (v.getId()) {
        case R.id.bLogin:
            String username = etUsername.getText().toString();
            String password = etPassword.getText().toString();

            User user = new User(username, password);

            authenticate(user);
            break;

    }



}



private void authenticate(User user)
{
    ServerRequests serverRequest = new ServerRequests(this);
    serverRequest.fetchUserDataAsyncTask(user, new GetUserCallback()
    {
        @Override
        public void done(User returnedUser) {
            if (returnedUser == null)
            {
                showErrorMessage();
            } else
            {
                logUserIn(returnedUser);
            }
        }
    });
}

private void showErrorMessage()
{
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(Login.this);
    dialogBuilder.setMessage("Incorrect user details");
    dialogBuilder.setPositiveButton("Ok", null);
    dialogBuilder.show();
}

private void logUserIn(User returnedUser)
{
    userLocalStore.storeUserData(returnedUser);
    userLocalStore.setUserLoggedIn(true);
    startActivity(new Intent(this, MainActivity.class));
}}

WAMP Server connection refuesed from Android Emulator

I am trying to connect to localhost WAMP Apache server from my android Emulator. But connections is getting refused. All the details provided below. Please help me out.

1) Android Logcat:

Error:

12-11 01:56:05.880  10346-32019/com.revu.revuappforcollege W/System.err﹕ org.apache.http.conn.HttpHostConnectException: Connection to http://10.0.2.2:80 refused

Complete Error message:

12-11 01:56:04.845  10346-10353/com.revu.revuappforcollege W/art﹕ Suspending all threads took: 178.509ms

12-11 01:56:04.947  10346-10369/com.revu.revuappforcollege W/EGL_emulation﹕ eglSurfaceAttrib not implemented

12-11 01:56:04.947  10346-10369/com.revu.revuappforcollege W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xad921ae0, error=EGL_SUCCESS

12-11 01:56:05.010  10346-10357/com.revu.revuappforcollege I/art﹕ Background partial concurrent mark sweep GC freed 2091(146KB) AllocSpace objects, 0(0B) LOS objects, 26% free, 1410KB/1922KB, paused 3.545ms total 623.566ms

12-11 01:56:05.015  10346-10346/com.revu.revuappforcollege I/Choreographer﹕ Skipped 44 frames!  The application may be doing too much work on its main thread.

12-11 01:56:05.143  10346-10353/com.revu.revuappforcollege W/art﹕ Suspending all threads took: 74.530ms

12-11 01:56:05.840  10346-10346/com.revu.revuappforcollege I/Choreographer﹕ Skipped 49 frames!  The application may be doing too much work on its main thread.

12-11 01:56:05.880  10346-32019/com.revu.revuappforcollege W/System.err﹕ org.apache.http.conn.HttpHostConnectException: Connection to http://10.0.2.2:80 refused

12-11 01:56:05.880  10346-32019/com.revu.revuappforcollege W/System.err﹕ at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:193)

12-11 01:56:05.880  10346-32019/com.revu.revuappforcollege W/System.err﹕ at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:169)

12-11 01:56:05.947  10346-10369/com.revu.revuappforcollege E/Surface﹕ getSlotFromBufferLocked: unknown buffer: 0xabfb9990

12-11 01:56:06.161  10346-10353/com.revu.revuappforcollege W/art﹕ Suspending all threads took: 82.626ms

12-11 01:56:06.493  10346-32019/com.revu.revuappforcollege W/System.err﹕ at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:124)

12-11 01:56:06.493  10346-32019/com.revu.revuappforcollege W/System.err﹕ at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:366)

12-11 01:56:06.493  10346-32019/com.revu.revuappforcollege W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:560)

12-11 01:56:06.493  10346-32019/com.revu.revuappforcollege W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:492)

12-11 01:56:06.646  10346-32019/com.revu.revuappforcollege W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:470)

12-11 01:56:06.646  10346-32019/com.revu.revuappforcollege W/System.err﹕ at com.revu.revuappforcollege.Activity1$readNFCTag.doInBackground(Activity1.java:336)

12-11 01:56:06.718  10346-32019/com.revu.revuappforcollege W/System.err﹕ at com.revu.revuappforcollege.Activity1$readNFCTag.doInBackground(Activity1.java:292)

12-11 01:56:06.718  10346-32019/com.revu.revuappforcollege W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:295)

12-11 01:56:06.718  10346-32019/com.revu.revuappforcollege W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:237)

12-11 01:56:07.136  10346-10353/com.revu.revuappforcollege W/art﹕ Suspending all threads took: 57.421ms
12-11 01:56:07.230  10346-32019/com.revu.revuappforcollege W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)

12-11 01:56:07.230  10346-32019/com.revu.revuappforcollege W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)

12-11 01:56:07.230  10346-32019/com.revu.revuappforcollege W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)

12-11 01:56:07.230  10346-32019/com.revu.revuappforcollege W/System.err﹕ at java.lang.Thread.run(Thread.java:818)

12-11 01:56:07.230  10346-32019/com.revu.revuappforcollege W/System.err﹕ Caused by: java.net.ConnectException: failed to connect to /10.0.2.2 (port 80): connect failed: ENETUNREACH (Network is unreachable)

12-11 01:56:07.269  10346-32019/com.revu.revuappforcollege W/System.err﹕ at libcore.io.IoBridge.connect(IoBridge.java:124)

12-11 01:56:07.269  10346-32019/com.revu.revuappforcollege W/System.err﹕ at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)

12-11 01:56:07.269  10346-32019/com.revu.revuappforcollege W/System.err﹕ at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:452)

12-11 01:56:07.269  10346-32019/com.revu.revuappforcollege W/System.err﹕ at java.net.Socket.connect(Socket.java:884)
12-11 01:56:07.269  10346-32019/com.revu.revuappforcollege W/System.err﹕ at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:124)

12-11 01:56:07.270  10346-32019/com.revu.revuappforcollege W/System.err﹕ at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:149)
12-11 01:56:07.270  10346-32019/com.revu.revuappforcollege W/System.err﹕ ... 14 more
12-11 01:56:07.270  10346-32019/com.revu.revuappforcollege W/System.err﹕ Caused by: android.system.ErrnoException: connect failed: ENETUNREACH (Network is unreachable)
 12-11 01:56:07.270  10346-32019/com.revu.revuappforcollege W/System.err﹕ at libcore.io.Posix.connect(Native Method)
 12-11 01:56:07.270  10346-32019/com.revu.revuappforcollege W/System.err﹕ at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:111)
12-11 01:56:07.270  10346-32019/com.revu.revuappforcollege W/System.err﹕ at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
 12-11 01:56:07.270  10346-32019/com.revu.revuappforcollege W/System.err﹕ at libcore.io.IoBridge.connect(IoBridge.java:122)
12-11 01:56:07.270  10346-32019/com.revu.revuappforcollege W/System.err﹕ ... 19 more



12-11 01:56:07.506  10346-32019/com.revu.revuappforcollege E/AndroidRuntime FATAL EXCEPTION: AsyncTask #1
Process: com.revu.revuappforcollege, PID: 10346
java.lang.RuntimeException: An error occurred while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:309)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
        at java.util.concurrent.FutureTask.run(FutureTask.java:242)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
        at java.lang.Thread.run(Thread.java:818)
 Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
        at android.os.Handler.<init>(Handler.java:200)
        at android.os.Handler.<init>(Handler.java:114)
        at android.widget.Toast$TN.<init>(Toast.java:345)
        at android.widget.Toast.<init>(Toast.java:101)
        at android.widget.Toast.makeText(Toast.java:259)
        at com.revu.revuappforcollege.Activity1$readNFCTag.doInBackground(Activity1.java:353)
        at com.revu.revuappforcollege.Activity1$readNFCTag.doInBackground(Activity1.java:292)
        at android.os.AsyncTask$2.call(AsyncTask.java:295)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
        at java.lang.Thread.run(Thread.java:818)
12-11 01:56:07.546  10346-10353/com.revu.revuappforcollege W/art﹕ Suspending all threads took: 13.659ms

2) I have added Permissionin Manifest file

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

3) Android code:

class readNFCTag extends AsyncTask<String, String, Void> {
  private ProgressDialog progressDialog = new ProgressDialog(Activity1.this);
  InputStream is;
  String result;

  protected void onPreExecute() {
    Log.e("BP4", "In onPreExecute");
    progressDialog.setMessage("Loading ...");
    progressDialog.show();
    result = "";
    is = null;

    progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
      @Override
      public void onCancel(DialogInterface arg0) {
        readNFCTag.this.cancel(true);
      }
    });
  }

  @Override
  protected Void doInBackground(String... params) {

    Log.e("BP5", "In doInBackground");

    HttpClient httpClient = new DefaultHttpClient();
    // HttpPost httpPost = new
    // HttpPost("http://10.0.2.2:8080/SomeName/Details.php");
    HttpPost httpPost = new HttpPost("http://10.0.2.2:80/AllainanceCanteen/NFCTagDetails.php");

    ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();

    try {

      Log.e("BP6", "In doInBackground2");
      param.add(new BasicNameValuePair("NFCTagNumber", Integer.toString(NFCTagNumber)));
      Log.e("BP8", "In doInBackground2");
      httpPost.setEntity(new UrlEncodedFormEntity(param));
      Log.e("BP9", "In doInBackground2");

      if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
      }
      Log.e("BP19", "In doInBackground: " + NFCTagNumber);
      HttpResponse httpResponse = httpClient.execute(httpPost);
      Log.e("BP10", "In doInBackground3");
      HttpEntity httpEntity = httpResponse.getEntity();
      Log.e("BP7", "In doInBackground3");
      // read content
      is = httpEntity.getContent();

    } catch (Exception e) {
      // Log.e("log_tag", "Error in http connection " + e.toString());
      // Log.e("####log_tag2", "End Here" + e.toString());

      // Log.e("!!!!log_tag", "Start Here");
      e.printStackTrace();
      // Log.e("***log_tag", "END HERE 2");

      Toast.makeText(getBaseContext(), "Cannot connect to server", Toast.LENGTH_LONG).show();
      this.progressDialog.dismiss();
      closeActivity();
    }
    try {

      BufferedReader br = new BufferedReader(new InputStreamReader(is));
      StringBuilder sb = new StringBuilder();
      String line;
      while (null != (line = br.readLine())) {
        sb.append(line).append("\n");
      }
      is.close();
      result = sb.toString();

    } catch (Exception e) {

      Log.e("log_tag2", "Error converting result " + e.toString());
      this.progressDialog.dismiss();
      Toast.makeText(getApplicationContext(), "Invalid NFC Communication!!", Toast.LENGTH_LONG).show();
      closeActivity();
    }

    return null;

  }

  protected void onPostExecute(Void v) {

    Log.e("Log_info", "REsults are: " + result + " End HERE");

    JSONObject Jarray = new JSONObject();

    try {

      try {
        Jarray = new JSONObject(result);
      } catch (Exception e) {
        this.progressDialog.dismiss();
        Toast.makeText(getApplicationContext(), "Invalid Communication!!", Toast.LENGTH_LONG).show();
        closeActivity();

      }

      if ((result.isEmpty()) || (result == null)) {

        // text.setText("Search Results Not found!!");
        this.progressDialog.dismiss();
        Toast.makeText(getApplicationContext(), "Invalid !!", Toast.LENGTH_LONG).show();
        closeActivity();

      } else {

        Log.e("BP7", "In doInBackground");
        for (int i = 0; i < Jarray.length(); i++) {

          Log.e("Log_info", "Results2 are: " + Jarray.toString() + " End HERE");
          // text_1 = (TextView)findViewById(R.id.txt1);
          seekReview = Jarray.getString("ProductName");

          addWidgetsToLayout();

          this.progressDialog.dismiss();

        }

      }
    } catch (Exception e) {

      Log.e("log_tag3", "Error parsing data " + e.toString());
      Toast.makeText(getApplicationContext(), "Cannot connect to server!!", Toast.LENGTH_LONG).show();
      closeActivity();
    }

  }
}

4) httpd.conf file Permissions are:

*Listen 0.0.0.0:80
Listen [::0]:80
<Directory />
    AllowOverride All
    Require all granted
</Directory>
<Directory "c:/wamp/bin/apache/apache2.4.9/cgi-bin">
    AllowOverride None
    Options None
    Require all granted
</Directory>

<Files ".ht*">
        Require all granted
</Files>*

5) No other software is using port 80

6) I also turnned off the Windows firewall and no anti virus in system.

7) I also tried with port 8080, but there is same problem

Android MultiPart Entity Causing App Crash

I am currently working on an android app that will allow the user to upload images to my server. I am new to android development so currently facing issues with sending the file to the server while using the Http MultiPartEntity

Given below is the code I am using for uploading the file to the server private class UploadFileToServer extends AsyncTask {

    @Override
    protected String doInBackground(Void... params) {
        return uploadFile();
    }

    @SuppressWarnings("deprecation")
    private String uploadFile() {
        String responseString = null;

        //Change URL here
        String FILE_UPLOAD_URL = SERVER_SUBMIT_URL;

        try {

            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(FILE_UPLOAD_URL);
            MultipartEntity reqEntity = new MultipartEntity();

            File file1 = new File(filePath1);
            FileBody bin1 = new FileBody(file1);
            reqEntity.addPart("image1", bin1);

            //Extras
            reqEntity.addPart("command", new StringBody("uploadImages"));

            post.setEntity(reqEntity);
            HttpResponse response = client.execute(post);
            resEntity = response.getEntity();

            responseString = EntityUtils.toString(resEntity);

            return responseString;

        } catch (Exception e) {
            Log.v(TAG, e.toString());
            responseString = e.toString();
        }

        return responseString;
    }

    @Override
    protected void onPostExecute(String result) {

        //Assuming JSON response From server
        // {"status": true, "ideaID" : 1}
        try{
            JSONObject json = new JSONObject(result);
            boolean status = json.getBoolean("status");
            if(status){
                showToast("Successfully Uploaded Images");

            }else{
                showToast("Image Uploading Failed");
            }

        }catch (Exception e) {
            showToast("Image Uploading Failed");
            Log.e(TAG, "Response from server: " + result + " " + e.getMessage());
        }
        // showing the server response in an alert dialog
        super.onPostExecute(result);
    }
}

I figured that the line "HttpResponse response = client.execute(post);" is where the app just crashed.

Here is the error that is shown in the log.

11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway /AndroidRuntime: FATAL EXCEPTION: AsyncTask #5
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime: java.lang.RuntimeException: An error occured while executing doInBackground()
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at java.util.concurrent.FutureTask.run(FutureTask.java:239)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at java.lang.Thread.run(Thread.java:838)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:  Caused by: java.lang.NoSuchFieldError: org.apache.http.message.BasicHeaderValueFormatter.INSTANCE
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at org.apache.http.entity.ContentType.toString(ContentType.java:153)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at org.apache.http.entity.mime.MultipartFormEntity.<init>(MultipartFormEntity.java:53)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at org.apache.http.entity.mime.MultipartEntityBuilder.buildEntity(MultipartEntityBuilder.java:236)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at org.apache.http.entity.mime.MultipartEntity.getEntity(MultipartEntity.java:119)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at org.apache.http.entity.mime.MultipartEntity.isChunked(MultipartEntity.java:138)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at org.apache.http.protocol.RequestContent.process(RequestContent.java:79)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at org.apache.http.protocol.BasicHttpProcessor.process(BasicHttpProcessor.java:290)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at org.apache.http.protocol.HttpRequestExecutor.preProcess(HttpRequestExecutor.java:167)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:413)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at com.example.grow.dubaiway.ImageActivity$UploadFileToServer.uploadFile(ImageActivity.java:197)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at com.example.grow.dubaiway.ImageActivity$UploadFileToServer.doInBackground(ImageActivity.java:156)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at com.example.grow.dubaiway.ImageActivity$UploadFileToServer.doInBackground(ImageActivity.java:137)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at java.lang.Thread.run(Thread.java:838) 

Could really use some help on the issue. Ive checked other posts but they didn't work for me.

Ive included the following libraries from the apache website. httpclient-4.5.1.jar httpclient-cache-4.5.1.jar httpcore-4.4.3.jar httpmime-4.5.1.jar

This is what my gradle file looks like apply plugin: 'com.android.application'

android {
   compileSdkVersion 23
   buildToolsVersion "23.0.2"

   defaultConfig {
       applicationId "com.example.neeraj.imageapp"
       minSdkVersion 14
       targetSdkVersion 23
       versionCode 1
       versionName "1.0"
   }
   buildTypes {
      release {
           minifyEnabled false
           proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
       }
   }

   packagingOptions {
       exclude 'META-INF/DEPENDENCIES.txt'
       exclude 'META-INF/LICENSE.txt'
       exclude 'META-INF/NOTICE.txt'
       exclude 'META-INF/NOTICE'
       exclude 'META-INF/LICENSE'
       exclude 'META-INF/DEPENDENCIES'
       exclude 'META-INF/notice.txt'
       exclude 'META-INF/license.txt'
       exclude 'META-INF/dependencies.txt'
   }
}

dependencies {
   compile fileTree(dir: 'libs', include: ['*.jar'])
   testCompile 'junit:junit:4.12'
   compile 'com.android.support:appcompat-v7:23.1.1'
   compile 'com.android.support:design:23.1.1'
}

Any help would be appreciated. Thanks

How to make JSONarray of object using MultipartEntity?

I have to post such json using MultipartEntity.

{
arrayName":[
  {
    // object one
  },
  {
    // object two
  }]
}

I don't get an idea how to make such structure once posting multipartEntity object, what i have tried so far is.

MultipartEntity entity = new MultipartEntity();
entity.addPart("key","value");
.....
.....
..... all keys 
httppost.setEntity(entity);

Is there any way so i can make MultipartEntity array or what?

NOTE: for separate posting one json object it work very fine. I just want to learn how to create JSONarry format, once posting with MultipartEntity.

"Result" returning NULL in Asynctask while calling API

I am calling an API through POST method and its constantly returning NULL. What could be the possible reason? I have posted the whole code. protected void onPostExecute(Void result) is actually getting NULL.

           public void makePostRequest()
{
    class makePostRequestAsyncTask extends AsyncTask<Void, Void, Void> {


        @Override
        protected Void doInBackground(Void... params) {

            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost("http://103.226.216.209/finger_varification/api/finger_verification");
            List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(7);
            nameValuePair.add(new BasicNameValuePair("sec_key", "2af8b9d956c39d2d52c46c2a02a978d1"));
            nameValuePair.add(new BasicNameValuePair("cnic", "3520214037921"));
            nameValuePair.add(new BasicNameValuePair("imei_no", "864121017028886"));
            nameValuePair.add(new BasicNameValuePair("device_name", "FingerMap5"));
            nameValuePair.add(new BasicNameValuePair("finger_index",index ));
            nameValuePair.add(new BasicNameValuePair("finger_template", model1.toString()));
            nameValuePair.add(new BasicNameValuePair("template_type", "RAW_IMAGE"));

            try {
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
            } catch (UnsupportedEncodingException e) {
                // log exception
                e.printStackTrace();
            }


            //making POST request.
            try {
                HttpResponse response = httpClient.execute(httpPost);
                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
                String response_body = reader.readLine();
                Log.d("Http Post Response:", String.valueOf(response));
              //  HttpResponse response = httpClient.execute(httpPost);
                // write response to log

              //  Log.d("Http Post Response:", response.toString());
            } catch (ClientProtocolException e) {
                // Log exception
                e.printStackTrace();
            } catch (IOException e) {
                // Log exception
                e.printStackTrace();
            }

            return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            if(null!=result /*.equals("working")*/){
                Toast.makeText(getApplicationContext(), "HTTP POST is working...", Toast.LENGTH_LONG).show();
            }else{
                Toast.makeText(getApplicationContext(), "Invalid POST req...", Toast.LENGTH_LONG).show();
            }
        }


    }
    makePostRequestAsyncTask NewTask= new makePostRequestAsyncTask();
    NewTask.execute();
}

Android Executing Post Requests

I'm attempting to send post requests from my android app, using the apache commons library but am running into some problems, probably due to my fundamental lack of understanding of the ASyncTasks

Here is the relevant code I have written

private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
    @Override
    protected Double doInBackground(String... params) {
        postData(params[0]);
        return null;
    }

};

    public void postData(String name) {

        //showMessage("Transaction timed out");

        HttpClient httpClient = new DefaultHttpClient();
        // replace with your url
        HttpPost httpPost = new HttpPost("http://posttestserver.com/post.php");


        //Post Data
        List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
        nameValuePair.add(new BasicNameValuePair("username", name));
        nameValuePair.add(new BasicNameValuePair("password", "123456789"));


        //Encoding POST data
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
        } catch (UnsupportedEncodingException e) {
            // log exception
            e.printStackTrace();
        }

        //making POST request.
        try {
            HttpResponse response = httpClient.execute(httpPost);
            // write response to log
            Log.d("Http Post Response:", response.toString());
        } catch (ClientProtocolException e) {
            // Log exception
            e.printStackTrace();
        } catch (IOException e) {
            // Log exception
            e.printStackTrace();
        }
}

   public void postClick(View v)
{
    new MyAsyncTask().doInBackground("JACK");
}

can post the stack trace if necessary, but I am probably just doing something silly wrong, but I cant figure out why