Android : How to parse JSON with local server

on Tuesday, March 31, 2015


I have a question about a local server and parsing JSON. I have to make a application for school and you have to parse JSON with a local server with IP and port.


This is the server class:



/**
* Created by Charlie on 26-3-2015.
*/
public class Server extends AsyncTask<Void, Void, String> {

private String message;
private String ip;
public static int port = 4444;
private String serverResponse = null;

public Server(String ip, int port, String message ) {
super();
//IP, Port en bericht om naar server te sturen
this.message = message;
this.ip = ip;
this.port = port;
}

@Override
protected String doInBackground(Void... params) {
try {
Socket serverSocket = new Socket();
serverSocket.connect(new InetSocketAddress(this.ip, this.port), 4444);

this.sendMessage(message, serverSocket);

InputStream input;

try {
input = serverSocket.getInputStream();
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(input));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line);
}
responseStreamReader.close();

this.serverResponse = stringBuilder.toString();

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


System.out.println("Response: " + serverResponse);

} catch (UnknownHostException e) {
Log.d("debug", "can't find host");
} catch (SocketTimeoutException e) {
Log.d("debug", "time-out");
} catch (IOException e) {
e.printStackTrace();
}
return serverResponse;
}

private void sendMessage(String message, Socket serverSocket) {
OutputStreamWriter outputStreamWriter = null;

try {
outputStreamWriter = new OutputStreamWriter(serverSocket.getOutputStream());
} catch (IOException e2) {
e2.printStackTrace();
}

if (outputStreamWriter != null) {
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
PrintWriter writer = new PrintWriter(bufferedWriter, true);

writer.println(message);
}
}
}


And this is a class which calls the data:



public class HoofdschermFragment extends android.app.Fragment {

public static String serverIp;
public static int serverPort = 4444;
public static ArrayList<String> slotenLijst;
public static ArrayList<JSONObject> beknopteInformatieSlotlijst;
public static String informatieslotbeknopt = null;
private static View rootview;
private Spinner sloten_spinner;
public static String SlotNaam;
public static Boolean initieleVerbinding = true;
public static int GeselecteerdSlot;
public static int GeselecteerdePositie;

public static android.app.Fragment fragmentslotinformatie = new InformatieSlotFragment();

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.fragment_hoofdscherm, container, false);

//als eerste keer verbinding is, haal alles op uit server, zo niet, laatst opgehaalde data weer invullen
if(initieleVerbinding == true) {
dataOphalen();
dataInvullen();
} else {
dataInvullen();
sloten_spinner.setSelection(GeselecteerdSlot);
}
return rootview;
}

public void dataOphalen() {

//ophalen van de services
slotenLijst = new ArrayList<String>();
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("slotenlijst", "");
} catch (JSONException e) {
e.printStackTrace();
}
String response = null;
try {
try {
// Dit IP adres moet IP adres van server zijn.
response = new Server(serverIp,
serverPort, jsonObject.toString()).execute().get();

} catch (ExecutionException e) {
e.printStackTrace();
}
} catch (InterruptedException e1) {
e1.printStackTrace();
}
if (response == null) {

Toast.makeText(rootview.getContext(), "Kan helaas geen verbinding maken met de server.", Toast.LENGTH_LONG).show();
} else {
// Haal de null naam weg van de JSONArray (Voorkomt error)
String jsonFix = response.replace("null", "");

JSONArray JArray = null;
try {
JArray = new JSONArray(jsonFix);
} catch (JSONException e) {
e.printStackTrace();
}

JSONObject jObject = null;
String value = null;
slotenLijst = new ArrayList<String>();

//zet alle services in een JArray
for (int i = 0; i < JArray.length(); i++) {
try {
jObject = JArray.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
try {
value = jObject.getString("Slot");
} catch (JSONException e) {
e.printStackTrace();
}
slotenLijst.add(value);

}
// korte informatie over elke dienst ophalen, in een ArrayList zetten als JSONObjecten
beknopteInformatieSlotlijst = new ArrayList<JSONObject>();
JSONObject beknoptjObject = new JSONObject();
try {
for (int i = 0; i < slotenLijst.size(); i++) {
beknoptjObject.put("Informatiebeknopt", slotenLijst.get(i));
try {
try {
informatieslotbeknopt = new Server(serverIp,
serverPort, beknoptjObject.toString()).execute().get();
//exceptions afvangen
} catch (ExecutionException e) {
e.printStackTrace();
}
} catch (InterruptedException e1) {
e1.printStackTrace();
}
String infoFix = informatieslotbeknopt.replace("null", "");
JSONObject fixedjObject = new JSONObject(infoFix);
beknopteInformatieSlotlijst.add(fixedjObject);

Log.i("Informatiebeknopt", infoFix);
}
} catch (JSONException e) {
e.printStackTrace();
}

//aangeven dat app al eens eerder gedraait heeft
initieleVerbinding = false;

}


// Locate the spinner in activity_main.xml
sloten_spinner = (Spinner) rootview.findViewById(R.id.spinner);

// Spinner adapter

sloten_spinner
.setAdapter(new ArrayAdapter<String>(rootview.getContext(),
android.R.layout.simple_spinner_dropdown_item,
slotenLijst));

// Spinner on item click listener
sloten_spinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

@Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
// Locate the textviews in activity_main.xml
TextView beknopteinfoslot = (TextView) rootview.findViewById(R.id.textviewbeknoptinfoslot);

try {
// Set the text followed by the position
beknopteinfoslot.setText(beknopteInformatieSlotlijst.get(position).getString("Informatiebeknopt"));
SlotNaam = slotenLijst.get(position);

} catch (Exception e) {

}

}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});

}

//opgehaalde data in de spinner zetten en beknopte tekst over diensten weergeven
private void dataInvullen() {
// Locate the spinner in activity_main.xml
sloten_spinner = (Spinner) rootview.findViewById(R.id.spinner);

// Spinner adapter
sloten_spinner
.setAdapter(new ArrayAdapter<String>(rootview.getContext(),
android.R.layout.simple_spinner_dropdown_item,
slotenLijst));

// Spinner on item click listener
sloten_spinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

@Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
// TODO Auto-generated method stub
// Locate the textviews in activity_main.xml
TextView beknopteinfo = (TextView) rootview.findViewById(R.id.textviewbeknoptinfoslot);

try {
// Set the text followed by the position
beknopteinfo.setText(beknopteInformatieSlotlijst.get(position).getString("informatieslotbeknopt"));
SlotNaam = slotenLijst.get(position);
getActivity().setTitle(SlotNaam);
} catch (Exception e) {

}

}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});

//naar servicepagina navigeren en dus informatie ophalen over de geselecteerdePositie
Button infoslotbutton = (Button) rootview.findViewById(R.id.infoslotbutton);
infoslotbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
GeselecteerdePositie = sloten_spinner.getSelectedItemPosition();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragmentslotinformatie)
.commit();
}
});

}
}


I have also an Activity where the user can fill in the IP, so that the app can make a connection with the server with the given IP.

I know how I can figure out my own local IP adres, but where should I put the JSON file with the information so that the app can read the JSON data from that file? What I don't mean is a local json file, I mean a JSON file on a local server which can be reached with a IP. Thanks in advance.


0 comments:

Post a Comment