0

I am developing an android application for the first time, and have some questions about parsing data in Java that is supplied from a Server via HTTP parsing. Right now, I am able to test a simple connection, respond with "Data Matched" and read that successfully. This means my server side code is correct, as well as how I grab the info.

My next step is to turn my PHP server response to JSON and send to Java. But I'm not sure how to get Java to read the JSON array I will be sending, and save the parts into accessible variables in Java.

I've reviewed the two following stackoverflow questions, but I'm still not sure how to implement that suggestion into my existing code.

How to parse a JSON and turn its values into an Array?

How to get data as an json array from a server and convert it in to java array to use in android application

MY CODE:

HttpParse:

package [domain_package].lexaapp;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by rachel.dimouro on 12/6/2017.
*/

public class HttpParse {

  String FinalHttpData = "";
  String Result ;
  BufferedWriter bufferedWriter ;
  OutputStream outputStream ;
  BufferedReader bufferedReader ;
  StringBuilder stringBuilder = new StringBuilder();
  URL url;

  public String postRequest(HashMap<String, String> Data, String HttpUrlHolder) {

    try {
        url = new URL(HttpUrlHolder);

        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

        httpURLConnection.setReadTimeout(14000);

        httpURLConnection.setConnectTimeout(14000);

        httpURLConnection.setRequestMethod("POST");

        httpURLConnection.setDoInput(true);

        httpURLConnection.setDoOutput(true);

        outputStream = httpURLConnection.getOutputStream();

        bufferedWriter = new BufferedWriter(

                new OutputStreamWriter(outputStream, "UTF-8"));

        bufferedWriter.write(FinalDataParse(Data));

        bufferedWriter.flush();

        bufferedWriter.close();

        outputStream.close();

        if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {

            bufferedReader = new BufferedReader(
                    new InputStreamReader(
                            httpURLConnection.getInputStream()
                    )
            );
            FinalHttpData = bufferedReader.readLine();
        }
        else {
            FinalHttpData = "Something Went Wrong";
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return FinalHttpData;
  }

  public String FinalDataParse(HashMap<String,String> hashMap2) throws UnsupportedEncodingException {

    for(Map.Entry<String,String> map_entry : hashMap2.entrySet()){

        stringBuilder.append("&");

        stringBuilder.append(URLEncoder.encode(map_entry.getKey(), "UTF-8"));

        stringBuilder.append("=");

        stringBuilder.append(URLEncoder.encode(map_entry.getValue(), "UTF-8"));

    }

    Result = stringBuilder.toString();

    return Result ;
  }
}

Java function To act on Data:

    public void SGSearchFunction(final String SearchInput){

    class SGSearchClass extends AsyncTask<String,Void,String> {

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

            progressDialog = ProgressDialog.show(DashboardActivity.this,"Loading Data",null,true,true);
        }

        @Override
        protected void onPostExecute(String httpResponseMsg) {

            super.onPostExecute(httpResponseMsg);

            progressDialog.dismiss();

            // is this where I should put the code for the array, or does it go in the HttpParse section?
            if(httpResponseMsg.equalsIgnoreCase("Data Matched")){ 

                finish();

                Intent intent = new Intent(DashboardActivity.this, SGInfoActivity.class);

                intent.putExtra(SearchValue, SearchInput);

                startActivity(intent);


            } else {

                Toast.makeText(DashboardActivity.this,httpResponseMsg,Toast.LENGTH_LONG).show();
            }

        }

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

            hashMap.put("SearchInput",params[0]);

            finalResultSearch = httpParse.postRequest(hashMap, HttpURL);

            return finalResultSearch;
        }
    }

    SGSearchClass sgSearchClass = new SGSearchClass();

    sgSearchClass.execute(SearchInput);
}

All help is appreciated.

Thanks!

6
  • 1
    I would suggest using a library such as retrofit for this. It provides you with the callback and parses the data for you as well. Retrofit Commented Jan 9, 2018 at 15:01
  • So the library can be pulled in with the import feature? And do you have suggestions for the best library to use? Commented Jan 9, 2018 at 15:20
  • 1
    Go throught this link. This is Retrofit, another choice is Volley. You need to add the dependency in your Gradle file. If you go through the documentation you'll see that they have a very good guide Commented Jan 9, 2018 at 15:25
  • What point you are not getting for parsing JSON in java ? Commented Jan 9, 2018 at 15:27
  • @Napster Thank you so much! Commented Jan 9, 2018 at 15:34

0

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.