1

In my project , to access the webservice am using http class which is not working properly and my project stops.

Can someone tell me an alternate way for accessing the webservice instead of using http. Thank you in advance

class httpclass {
    String result;

    public String server_conn(String user_url) 
    {
        // String user_url="";

        String user_url3=user_url.replaceAll(" ","%20");
        String user_url2=user_url3.replaceAll("\n","%0D");


        HttpClient client = new DefaultHttpClient();
        HttpGet siteRequest = new HttpGet(user_url2);
        StringBuilder sb = new StringBuilder();

        HttpResponse httpResponse;

        try {
            httpResponse = client.execute(siteRequest);
            HttpEntity entity = httpResponse.getEntity();
            InputStream in = entity.getContent();

            String line = null;
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(in));
            while ((line = reader.readLine()) != null)
            {

                sb.append(line);

            }

            result = sb.toString();

        } catch (ClientProtocolException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

}

log in form

public class LoginForm extends FragmentActivity {
    /** Called when the activity is first created. */

    TextView txt1, txt2, err,forget;
    EditText name;
    EditText pass;
    Button click,vend;
    CheckBox savepass;
    Button newuser;
    Button signin;
    @SuppressWarnings("unused")
    private Cursor signin1;


    SharedPreferences sharedPreferences=null;

    public static String str1, str2;
    public static String result;
    public  static String username;
    ProgressDialog myProgressDialog = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);       BugSenseHandler.initAndStartSession(this, "68640bea");
        setContentView(R.layout.login);


        vend=(Button)findViewById(R.id.vend);
        name = (EditText) findViewById(R.id.username);
        pass = (EditText) findViewById(R.id.password);
        savepass=(CheckBox)findViewById(R.id.savepass);
        Button  cancel = (Button) findViewById(R.id.cancel);
        //Button  back = (Button) findViewById(R.id.back);
        cancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {   

                Intent second = new Intent( LoginForm.this,canceluser.class);   

                startActivity(second);
                finish();

            }

        });

        sharedPreferences=PreferenceManager.getDefaultSharedPreferences(this);

        String name1=sharedPreferences.getString("p_name", "");
        name.setText(name1.toString());

        String pass1=sharedPreferences.getString("p_pass", "");
        pass.setText(pass1.toString());


       //s forget=(TextView)findViewById(R.id.forget);
        signin = (Button) findViewById(R.id.signin);
        click = (Button) findViewById(R.id.click);
        newuser = (Button) findViewById(R.id.signup);
        vend.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent viewIntent =
                          new Intent("android.intent.action.VIEW",
                            Uri.parse("http://www.iwedplanner.com/vendor/vendorhome.aspx"));
                          startActivity(viewIntent);
            }});

        click.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent1 = new Intent(LoginForm.this, forgetpwd.class);
                startActivity(intent1);
                finish();
            }});

        signin.setOnClickListener(new OnClickListener() 
        {
            @Override
            public void onClick(View v) {


                if(name.getText().toString().equals(""))
                {
                alertbox("Message!","Enter Your Username");
                name.requestFocus();
                }
            else if(pass.getText().toString().equals(""))
                {
                alertbox("Message!","Enter Your Password");
                pass.requestFocus();
                }
                else
                {
                str1 = name.getText().toString();
                str2 = pass.getText().toString();

                boolean value = false;
                // validuser();
                ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);


                NetworkInfo info = cm.getActiveNetworkInfo();
                if (info != null && info.isAvailable()) {
                               value = true;


                    openconn(str1, str2);


                }
                else
                {
                    alertbox("Message!", "No Internet Connection!");
                }
            }
            }

        });

        newuser.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                newuser();

            }
        });

    }

    public void openconn(String strr1, String strr2) 
    {

        if (!strr1.equals("") && !strr2.equals(""))

        {
            err = (TextView) findViewById(R.id.err);

        //  String user_url = "http://iwedplanner.com/mobile/MLogin.aspx?uname="+ strr1 + "&pwd=" + strr2;

            String user_url="http://mobileapps.iwedplanner.com/mobileapps/iwedplanner/mobile/MLogin.aspx?uname="+ strr1 + "&pwd=" + strr2;



            httpclass obj = new httpclass();
            result = obj.server_conn(user_url);

          //  alertbox("",""+result);

            if (result != null) 
            {
                StringTokenizer st = new StringTokenizer(result, "|");
                result = st.nextToken();

                if (result.equals("InvalidUser ")) 
                {


                    Dialog locationError = new AlertDialog.Builder(
                            LoginForm.this).setIcon(0).setTitle("Message!")
                            .setPositiveButton(R.string.yes, null).setMessage(
                                    "Sorry, Invalid Username or Password ")
                            .create();
                    locationError.show();
                    name.requestFocus();
                } 
                else if(result.equals(strr1)) 
                {
                    // Toast.makeText(getBaseContext(),"Valid User",Toast.LENGTH_SHORT).show();

                    if(savepass.isChecked())
                    {
                        SharedPreferences.Editor editor=sharedPreferences.edit();
                        editor.putString("p_name",name.getText().toString());                        
                        //editor.putString("p_pass",pass.getText().toString());
                        editor.commit();
                    }
                    else
                    {
                        SharedPreferences.Editor editor=sharedPreferences.edit();
                        editor.putString("p_name", "");
                        editor.putString("p_pass","");
                        editor.commit();
                    }
                    validuser();
                }

                else
                {
                    alertbox("Message!","Error in network connection");
                }
            }

        }
    }

    public void validuser() 
    {

    username=str1;

        name.setText("");
        pass.setText("");           
        Intent userintent = new Intent(this, welcomeuser1.class);
        //userintent.putExtra("name5",str1);    

      //Intent userintent=new Intent(this,WeddingInfo.class);
        startActivity(userintent);
        finish();   



    }

    public void newuser() {

        Intent userintent1 = new Intent(this, newuserform.class);
        startActivity(userintent1);
        finish();
    }
    protected void alertbox(String title, String mymessage) {
        new AlertDialog.Builder(this)
                .setMessage(mymessage)
                .setTitle(title)
                .setCancelable(true)
                .setNeutralButton(android.R.string.ok,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                    int whichButton) {
                            }
                        }).show();
    }
    @Override
      public void onStart() {
        super.onStart();
       // The rest of your onStart() code.
        // //  EasyTracker.getInstance(this).activityStart(this);  // Add this method.
      }

      @Override
      public void onStop() {
        super.onStop();
        // The rest of your onStop() code.
        // EasyTracker.getInstance(this).activityStop(this);  // Add this method.
      }
}

Error:duplicate files during packaging of APK C:\Users\sentientit\Documents\Wed Studio\app\build\outputs\apk\app-debug-unaligned.apk

Path in archive: META-INF/LICENSE.txt

Origin 1: C:\Users\sentientit\Documents\Wed Studio\app\libs\twitter4j.jar

1 Origin 2: C:\Users\sentientit.gradle\caches\modules-2\files-2.1\joda- time\joda-time\2.4\89e9725439adffbbd41c5f5c215c136082b34a7f\joda-time-2.4.jar

You can ignore those files in your build.gradle:

android {
  packagingOptions {
    exclude 'META-INF/LICENSE.txt'
  }
}

Error:Execution failed for task ':app:packageDebug'.

Duplicate files copied in APK META-INF/LICENSE.txt File 1: C:\Users\sentientit\Documents\Wed Studio\app\libs\twitter4j.jar

File 2: C:\Users\sentientit\.gradle\cache``s\modules-2\files-2.1\joda-time\joda-time\2.4\89e9725439adffbbd41c5f5c215c136082b34a7f\joda-time-2.4.jar
10
  • show your code @vimal Commented Jul 24, 2015 at 5:16
  • Smells like a NetworkOnMainThreadException Commented Jul 24, 2015 at 5:33
  • right @geraldschneider .... Commented Jul 24, 2015 at 5:44
  • right now it's just guessing, if you want help you have to post the output of LogCat. Commented Jul 24, 2015 at 6:03
  • Check this androhub.com/android-json-parser) bro. Hope you get little help. Commented Jul 24, 2015 at 6:26

3 Answers 3

1

You can do this way:

AsyncTask for Web service:

private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
    ProgressDialog pdLoading = new ProgressDialog(AsyncExample.this);

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
        pdLoading.setMessage("Loading...");
        pdLoading.show();
    }
    @Override
    protected Void doInBackground(Void... params) {

        String serverGETResponse = getJsonDataStringFormat("Your_Url", "GET", "", "LOGIN_ACTIVITY");
        String serverPOSTResponse = getJsonDataStringFormat("Your_Url", "POST", "YOUR_JSON_STRING", "LOGIN_ACTIVITY");    
        return null;
    }

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

        //this method will be running on UI thread

        pdLoading.dismiss();
       }

    }

Now Get Response from server in Background thread:

public static String getJsonDataStringFormat(String url, String method,String jObjStr, String tag) {
        InputStream is = null;
        String Root_Response = null;
        HttpResponse httpResponse;
        HttpParams httpParameters = new BasicHttpParams();
        DefaultHttpClient httpClient;
        HttpConnectionParams.setConnectionTimeout(httpParameters,connectionTimeOut);
        HttpConnectionParams.setSoTimeout(httpParameters, socketTimeOut);
        try {
            httpClient = new DefaultHttpClient(httpParameters);
            url = url.replace(" ", "%20");
            if (method == "POST") {
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new StringEntity(jObjStr));
                httpResponse = httpClient.execute(httpPost);
                is = httpResponse.getEntity().getContent();
            } else if (method == "GET") {
                HttpGet httpGet = new HttpGet(new URI(url));
                httpResponse = httpClient.execute(httpGet);
                is = httpResponse.getEntity().getContent();
            }

            Root_Response = convertStreamToString(is);
            Log.i(tag, Root_Response);

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

        return Root_Response;
    }

Convert Server's Response to String:

public static String convertStreamToString(InputStream inputStream)
            throws IOException {
        if (inputStream != null) {
            StringBuilder sb = new StringBuilder();
            String line;
            try {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(inputStream, "UTF-8"));
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\n");
                }
            } finally {
                inputStream.close();
            }
            return sb.toString();
        } else {
            return "";
        }
    }

Hope it will help you.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you Hiren Pate It got cleared.I got another error like 1.Duplicate files during packaging and 2.Duplicate files copied inAPK-META-INF/LICENSE.txt
0

call the method server_conn() inside AsyncTask , and pass the url

private class AsyncTaskTest extends AsyncTask<String, Void, Void>
{
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(String... strings) {
        server_conn(strings[0]);
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
    }
}

and call the asynctastk using below syntax

new AsyncTaskTest().execute(url);

1 Comment

I cant find Async Task.how can i call
0

You are facing NetworkOnMainThread exception all you have to do is add this code :

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
     .detectAll()
     .penaltyLog()
     .build();
 StrictMode.setThreadPolicy(policy); 

For more details you can check developer site.

5 Comments

Where i should add it
inside your onCreate() method.
Thank you so much Surender Kumar its working.but while importing to android studio i getting a new error like "duplicate files during packaging of APK
It occur if you have two files importing..Please check your imports.
its an existing eclipse project while importing it android studio i got this error.Am posting my LogCat please make a read on it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.