-3

I am new to android development and I am trying to make an android app for a class project that lets the user order food. Once they hit the checkout button, there is a String value containing the user's order information(i.e. -Chicken Sandwich, tomatoes, lettuce, mayo, special instructions, total: $5.99) that is passed to the next activity. However, I also want this information to be sent from the app to a website, so that the person viewing the webpage can see the order information. What is the best way to go about this?

I sort of figured out how to handle user login/registration with MySQL and phpmyadmin, but I'm not sure if doing that again for this specific string is the best way to display the food order. I'm not looking to create a database specifically for one String. Instead I just want to post that order information on a webpage so that a "staff member" can view the order information and start working on the food order.

I found some info from this post: How to send a data to a web server from Android

Here is what I tried so far based on what I found from that post : Orderlist activity:

@Override
public void onClick(View v) {
    Intent myIntent = null;
    switch (v.getId()) {
        case R.id.checkout:
            if (MainActivity.amountBalance - orderPrice < 0) {
                Toast.makeText(Orderlist.this, "Insufficient balance!", Toast.LENGTH_SHORT).show();
            } else {
                MainActivity.amountBalance = MainActivity.amountBalance - orderPrice;
                myIntent = new Intent(Orderlist.this, OrderPlaced.class);
                Toast.makeText(getApplicationContext(),"Your order was placed!",Toast.LENGTH_LONG).show();
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://mywebsitename.com/mypage.php");
                try {
                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);

                    nameValuePairs.add(new BasicNameValuePair("orderinfo", "Chicken sandwich: tomatoes, onions, cheese.\nTotal: $5.99."));
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    httpclient.execute(httppost);

                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                }
                startActivity(i);
            }
            break;
        case R.id.cancel:
            i = new Intent(Orderlist.this, MainActivity.class);
            Toast.makeText(Orderlist.this, "All items have been removed from cart.", Toast.LENGTH_LONG).show();
            startActivity(i);
            break;


    }
}

mypage.php

<?php
$filename="datatest.html";
file_put_contents($filename,$_POST["orderinfo"]."<br />",FILE_APPEND);
$msg=file_get_contents($filename);
echo $msg; ?>

Unfortunately this causes my code to crash and doesn't post anything to mypage.php. How do I fix this?

Error: FATAL EXCEPTION: main
Process: com.example.kusha.finalproject, PID: 5291

android.os.NetworkOnMainThreadException
                                                                              at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)
                                                                              at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:86)
                                                                              at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:74)
                                                                              at java.net.InetAddress.getAllByName(InetAddress.java:752)
                                                                              at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:142)
                                                                              at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:169)
                                                                              at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:124)
                                                                              at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:366)
                                                                              at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:560)
                                                                              at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:492)
                                                                              at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:470)
                                                                              at com.example.kusha.finalproject.Orderlist.onClick(Orderlist.java:192)
                                                                              at android.view.View.performClick(View.java:5637)
                                                                              at android.view.View$PerformClick.run(View.java:22429)
                                                                              at android.os.Handler.handleCallback(Handler.java:751)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                              at android.os.Looper.loop(Looper.java:154)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

-- And the error appears to be coming from Orderlist.java:192 which is this piece of code here:

 nameValuePairs.add(new BasicNameValuePair("orderinfo", "Chicken sandwich: 
 tomatoes, onions, cheese.\nTotal: $5.99."));
 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
 httpclient.execute(httppost); //ERROR FROM HERE

Thank You!

Community
  • 1
  • 1
pshaun
  • 47
  • 6

1 Answers1

0

You should read about Restful Web service. the Android sends Http Request with Json(or XML) String data (optional) to the server.Server (.Net MVC, Spring MVC, PHP ...) receives that request, process it with business logic, update database and return a Json String result to Android. After login success, server MUST send a token to mobile, android store this token for Authenticate next requests. In your case, you could use Http Request POST, post Json data from android to server. For more flexible, you could use DTO serialize with Flexjson or Gson library for data. You wonder how to do that, see bellow code

public static String httpPost(String domain, String root, String body,
        String token, String username)
{
    String urlString = "http://"+domain+"/"+root;

    Log.d("httpPost-url",
            " url:"+urlString+
            " ,token:"+token+
            " ,httpPost-body:"+ body+
            " ,username:"+username);

    StringBuffer response = new StringBuffer();
    try {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        if(token!=null)
        {
            conn.setRequestProperty("Authorization", "Basic " + token);
        }
        if(username!=null)
        {
            conn.setRequestProperty("Username", username);
        }
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(body);
        writer.flush();
        BufferedReader br = null;
        try
        {
            Log.d("HttpUtil", "Http code:" + conn.getResponseCode());

            br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
        }
        catch (IOException e)
        {
            e.printStackTrace();
            br = new BufferedReader(new InputStreamReader((conn.getErrorStream())));
        }
        String inputLine;
        while ((inputLine = br.readLine()) != null)
        {
            response.append(inputLine);
        }
        System.out.println("result from server:"+response.toString());
        conn.disconnect();

    }
    catch (Exception e)
    {
        e.printStackTrace();
        return null;
    }
    return  response.toString();
}


public static String httpGet(String domain, String urlRoot, String token,
                             String username)
{
    String urlString = "http://"+domain+"/"+urlRoot;
    Log.d("httpGet-url:",
            " url:"+urlString+
            " ,token:"+token+
            " ,username:"+username);
    StringBuffer response = new StringBuffer();
    try {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-Type", "application/json");
        if(token!=null)
        {
            conn.setRequestProperty("Authorization", "Basic " + token);
        }
        if(username!=null)
        {
            conn.setRequestProperty("Username", username);
        }
        Log.d("HttpUtil","Http code:"+conn.getResponseCode());

        BufferedReader br=null;

        if(conn.getResponseCode()>=200&&conn.getResponseCode()<300) {
            br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
        }
        else if(conn.getResponseCode()>=400)
        {
            br = new BufferedReader(new InputStreamReader((conn.getErrorStream())));
        }

        String inputLine;
        while ((inputLine = br.readLine()) != null) {
            response.append(inputLine);
        }

        System.out.println("result from server:"+response.toString());

        conn.disconnect();

    } catch (Exception e) {

        e.printStackTrace();
        return null;
    }
    return  response.toString();
}

Enjoy coding !

EDIT 1

android.os.NetworkOnMainThreadException

You should Use

AsyncTask or Handler

private class LoginTask extends AsyncTask<String, Void, String> {

    private ProgressDialog progress;

    protected String doInBackground(String... params)
    {
        LoginActivity.this.runOnUiThread(new Runnable() {
            public void run() {
                progress = new ProgressDialog(LoginActivity.this);
                progress.setTitle(getResources().getString(R.string.app_name));
                progress.setMessage(getResources().getString(R.string.loading));
                progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                progress.setCancelable(true);
                progress.show();
            }
        } );

        String result = HttpUtil.httpPost(
                params[0],params[1],
                params[2], params[3],
                params[4]);

        return result;
    }

    protected void onPostExecute(String param) {
        progress.dismiss();

        if(param==null)
        {
            return ;
        }
        Log.d("onPostExecute:",param);
        try
        {
            LoginDTO result = new JSONDeserializer<LoginDTO>()
                    .use("data", DataLoginDTO.class)
                    .use("data.rights.values", RightObjectDTO.class)
                    .deserialize(param, LoginDTO.class);
            if(result.getData()!=null)
            {
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                //intent.putExtra;
                Bundle bundle = new Bundle();
                //bundle.putParcelableArrayList("rights", result.getData().getRights());

                String rightString= new JSONSerializer().serialize(result.getData().getRights());

                intent.putExtras(bundle);
                String token = result.getData().getToken();
                SharedPreferences sharedPref = LoginActivity.this.getSharedPreferences(getResources()
                        .getString(R.string.preference_file_key),  Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPref.edit();
                editor.putString("token", token);
                editor.putString("username", usernameEditText.getText().toString());
                editor.putLong("employeeId", result.getData().getEmployeeId());
                editor.putString("rights", rightString);
                editor.commit();

                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                    startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(LoginActivity.this).toBundle());
                }
                else
                {
                    startActivity(intent);
                }

            }
            else
            {
                android.app.AlertDialog dialog = new android.app.AlertDialog.Builder(LoginActivity.this)
                        .setTitle(R.string.app_name)
                        .setMessage(R.string.incorrect_username_or_password)
                        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which)
                            {
                                dialog.dismiss();
                            }
                        })
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .show();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            AlertDialog dialog = new AlertDialog.Builder(LoginActivity.this)
                    .setTitle(R.string.error)
                    .setMessage(R.string.an_error_has_occurred)
                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .show();

        }
    }
}
Tung Vo
  • 2,227
  • 5
  • 27
  • 45
  • Thanks, i am looking into that. I'm still a bit confused however. Since I'm only trying to post a single string on the php page, would I change the parameters to just "public static String httpPost(String domain, String root, String body, String token)" and eliminate the username? Since i'm not using registration here. – pshaun May 08 '17 at 02:08
  • yes, do any thing you want :). use Http POST for Create data, GET for retrieve data, PUT for modify, DELETE for delete data – Tung Vo May 08 '17 at 02:11
  • Very admirable... congrats – statosdotcom May 08 '17 at 02:19
  • Okay! Also I'm a bit confused on token values. What exactly is my value supposed to be if I wanted to post that string to the php page? Or how would I find this value. – pshaun May 08 '17 at 02:20
  • Token is Hash String, you could read more abour it in stackoverflow – Tung Vo May 08 '17 at 02:26