Category Archives: android-studio

Error while importing http packages in android studio 2.1

Hey there I am importing few http packages for communication but I am getting error in these lines:

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

I am using latest android studio. Any help regarding importing these packages? I came to know that http packages are deprecated for android. To use above mentioned packages which package should I import ? Thank you.

Using org.appache.http.client in android studio

I'm using org.apache.http.client in the app I recently moved from Eclipse to Android Studio and I meet a new problem. Despite the fact that I have added a dependency to org.apache.httpComponents.httpCore_4.4.4.jar, which caused errors in the editor to disappear, when building the project, I get the following error message : "error : package org.apache.http.client does not exist".

Where am I wrong and what should I do to correct the problem?

Compatibility with HttpClient and SDK v23

first I apologize for my bad English . My problem is I can not reconcile two codes that run on different versions of Android, as they are:

    import org.apache.http.client.HttpClient; (This work with 22)
    import com.github.paolorotolo.appintro.AppIntro;(This work with 23)

If I set my project to version 22 , it works only HTTPClient , but changing to 23 does not recognize it , but it works the AppIntro . Attachment " build.gradle " and the error output in each case . I have to work with both because they are perfectly suited to my project , ironically

    apply plugin: 'com.android.application'

    android {
compileSdkVersion 22
buildToolsVersion "22.0.1"

defaultConfig {
    applicationId "com.example.victo.cqbo_definitive"
    minSdkVersion 15
    targetSdkVersion 22
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:22.2.0'
    compile 'com.github.paolorotolo:appintro:3.4.0'
}


Error:(3) Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Inverse'.
Error:(24) Error retrieving parent for item: No resource found that matches the given name 'android:Widget.Material.Button.Colored'.
Error:Execution failed for task ':app:processDebugResources'.
> com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Users\victo\AppData\Local\Android\sdk\build-tools\22.0.1\aapt.exe'' finished with non-zero exit value 1

Thank you very much in advance, I hope will help me with a solution c

Compatibility with HttpClient and SDK v23

first I apologize for my bad English . My problem is I can not reconcile two codes that run on different versions of Android, as they are:

    import org.apache.http.client.HttpClient; (This work with 22)
    import com.github.paolorotolo.appintro.AppIntro;(This work with 23)

If I set my project to version 22 , it works only HTTPClient , but changing to 23 does not recognize it , but it works the AppIntro . Attachment " build.gradle " and the error output in each case . I have to work with both because they are perfectly suited to my project , ironically

    apply plugin: 'com.android.application'

    android {
compileSdkVersion 22
buildToolsVersion "22.0.1"

defaultConfig {
    applicationId "com.example.victo.cqbo_definitive"
    minSdkVersion 15
    targetSdkVersion 22
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:22.2.0'
    compile 'com.github.paolorotolo:appintro:3.4.0'
}


Error:(3) Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Inverse'.
Error:(24) Error retrieving parent for item: No resource found that matches the given name 'android:Widget.Material.Button.Colored'.
Error:Execution failed for task ':app:processDebugResources'.
> com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Users\victo\AppData\Local\Android\sdk\build-tools\22.0.1\aapt.exe'' finished with non-zero exit value 1

Thank you very much in advance, I hope will help me with a solution c

Gradle erroneously throwing DuplicateFileException for different files

I'm trying to move an Eclipse project, k9mail, to Android Studio, but I'm getting a build error because gradle thinks two of my JAR files are the same:

Error:Execution failed for task ':transformResourcesWithMergeJavaResForDebug'.
> com.android.build.api.transform.TransformException:     com.android.builder.packaging.DuplicateFileException: Duplicate files copied in     APK META-INF/DEPENDENCIES
File1: C:\k-9\libs\apache-mime4j-dom-0.7.2.jar
File2: C:\k-9\libs\apache-mime4j-core-0.7.2.jar

Anyone know what's going on?

Send sms through android emulator and get it in mysql database or post it to a url/php script

I am working on a android application which can send a SMS to a predefined no. I want that, the SMS send by mobile will receive by My apache server.

I surf net a lot. There are many services which provides-

  1. A virtual no to send sms

  2. When virtual no received a sms, it posted(May be Get Request) this to a predefined URL and data may be processed further.

These services are not free.

I just want to test all this on my local machine with Android Emulator, Apache Server and whatever needed.

crashing while using http request android studio

I'm trying to create an online listview which populating from json array my code is from a famous tutorial web site but the codes do not work and crash,

MainActivity:

package ir.codelife.jokeline;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MainActivity extends ListActivity{
private DrawerLayout mDrawerLayout;
private TabLayout tabLayout;
private ViewPager viewPager;
// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> productsList;

// url to get all products list
   private static String url_all_products = "http://10.0.2.2/get_all_jokes.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "jokes";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "author";
private static final String TAG_MATN = "matn";

// products JSONArray
JSONArray products = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Hashmap for ListView
    productsList = new ArrayList<HashMap<String, String>>();

    // Loading products in Background Thread
    new LoadAllProducts().execute();

    // Get listview
    ListView lv = getListView();

    // on seleting single product
    // launching Edit Product Screen
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            // getting values from selected ListItem
            String pid = ((TextView) view.findViewById(R.id.pid)).getText()
                    .toString();

            // Starting new intent
            // sending pid to next activity

            // starting new activity and expecting some response back
        }
    });

}

// Response from Edit Product Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // if result code 100
    if (resultCode == 100) {
        // if result code 100 is received
        // means user edited/deleted product
        // reload this screen again
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }

}

/**
 * Background Async Task to Load all product by making HTTP Request
 * */
class LoadAllProducts extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("درحال بارگزاری جوک ها ");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", null);

        // Check your log cat for JSON reponse
        Log.d("All Products: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found
                // Getting Array of Products
                products = json.getJSONArray(TAG_PRODUCTS);

                // looping through All Products
                for (int i = 0; i < products.length(); i++) {
                    JSONObject c = products.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_PID);
                    String matn = c.getString(TAG_NAME);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_PID, id);
                    map.put(TAG_NAME, matn);

                    // adding HashList to ArrayList
                    productsList.add(map);
                }
            } else {
                // no products found
                // Launch Add New product Activity

                // Closing all previous activities
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        MainActivity.this, productsList,
                        R.layout.list_item, new String[] { TAG_PID,
                        TAG_NAME},
                        new int[] { R.id.pid, R.id.name });
                // updating listview
                setListAdapter(adapter);
            }
        });

    }

}



}

and my json parse class

package ir.codelife.jokeline;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;
    import java.util.List;

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.client.utils.URLEncodedUtils;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.json.JSONException;
    import org.json.JSONObject;

    import android.util.Log;

 public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
      public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
                                  List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}
}

and I use compile'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2' library for android studio to use http request; I delete every line of code and I undranstand that my problem is these lines:

   List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", null);

Can’t solve Warning:Unable to find optional library: org.apache.http.legacy

I'm following a tutorial it worked smoothly at first but some deprecated problems got in. I'm new in programming and I tried some of the solutions that i've read but none of them worked on to solve this problem. I also tried to pasting some code on org.apache.http.legacy which is located on C:\Users\Username\AppData\Local\Android\sdk\platforms\android-23\optional.. BUT i dont know how to open that file so i tried opening it using notepad++.... the code look like this..

 [
  {
    "name": "org.apache.http.legacy",
    "jar": "org.apache.http.legacy.jar",
    "manifest": false
  }
]

I also tred adding an extension filename on the useLibrary 'org.apache.http.legacy' .. like useLibrary 'org.apache.http.legacy.jar' but nothing happened..

And Also changing different classpath like..

classpath 'com.android.tools.build:gradle:1.5.0'
classpath 'com.android.tools.build:gradle:1.3.1'
classpath 'com.android.tools.build:gradle:1.3.0'

Even changin the

 compileSdkVersion 23
 buildToolsVersion "23.0.2"

And a lot of stuff trying paste, change, delete, cut and replace having some sort of trial and error.. this stuff i made was n a comment because i'm having a rial and error on them..

//    compile fileTree(dir: 'libs', include: ['*.jar'])
//    compile files('libs/org.apache.http.legacy.jar')


///////////////
//compile 'com.google.http-client:google-http-client-android:+'
//
//compile 'com.google.api-client:google-api-client-android:+'
//
//compile 'com.google.api-client:google-api-client-gson:+'
//
//compile 'com.google.code.gson:gson:2.2.4'
}


//apply plugin: 'com.android.application'
//
//android {
//         compileSdkVersion 23
//      buildToolsVersion "23.0.2"
//
//    defaultConfig {
//        applicationId "com.example.--------.-----------"
//        minSdkVersion 19
//        targetSdkVersion 23
//    }
//    buildTypes {
//        release {
//            minifyEnabled false
//            proguardFiles getDefaultProguardFile('proguard-android.txt'),             'proguard-rules.pro'
//        }
//    }
//
//}
//
//dependencies {
//
//    compile project(':comtaxibulgariamap_mapsforge_044201406271417533')
//    compile fileTree(include: ['*.jar'], dir: 'libs')
//}

build.gradle(Module:app

build.gradle(MyProjectName

I really appreciate any help you can provide.