daniel
daniel

Reputation: 123

Convert JSON to string from SQL DB with PHP

I have an app that should display a string in a textview after the buttons are clicked; instead it displays the JSON format of the code, not the uncoded JSON. Here is my android code:

    package game.com;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class JSONtestActivity extends Activity {

String result = "";
InputStream is = null;


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

    Button btn = (Button) findViewById(R.id.button1);
    btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            TextView one = (TextView) findViewById(R.id.textView1);

            returnJson();

        //end of onClick    
        }
    //end of onClickListener
    });


//end of oncreate()    
}

public void returnJson(){

    TextView one = (TextView) findViewById(R.id.textView1);

    try{
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new       HttpPost("http://10.0.2.2/textures_story_list.php");

            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

    }catch(Exception e) {
        one.setText("error3");
    }

    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();
            result = sb.toString();

    }catch(Exception e) {
        one.setText("error2");          
        }

    try{
        JSONArray jArray = new JSONArray(result);
        for(int i = 0;i<jArray.length();i++){
            JSONObject json_data = jArray.getJSONObject(i);
            Log.i("log_tag","story_name: "+json_data.getString("story_name") 
                    );
            result += "\n" + jArray.getJSONObject(i); 



        }
        one.setText(result);
    }
    catch(JSONException e) {
        one.setText("error1");
    }
        return;


//end of returnJson()   
}



//end of class body    
}

and my php

<?php 
mysql_connect("127.0.0.1","root");
mysql_select_db("textures_story_list");
$sql=mysql_query("SELECT story_name FROM story_list WHERE story_name LIKE 'sto%'");
while($row=mysql_fetch_assoc($sql)) $output[]=$row;
print(json_encode($output));
mysql_close();
?>

Can someone help with this? It doesn't display the names instead of the json format. This is what it displays in the textview instead of "story one", "story two" and so on:

[{"story_name":"Story One"}
 {"story_name":"Story Two"}, 
 {"story_name":"Story Three"}, 
 {"story_name":"Story Four"},
 {"story_name":"Story Five"},
 {"story_name":"Story Six"}]/n{"story_name":"Story One"},
 {"story_name":"Story Two"},
 {"story_name":"Story Three"},
 {"story_name":"Story Four"},
 {"story_name":"Story Five"},
 {"story_name":"Story Six"}

Upvotes: 1

Views: 754

Answers (1)

Boris Strandjev
Boris Strandjev

Reputation: 46963

I might be too much of a preacher, but every time it comes to parsing string to objects in java I recommend using Gson library. It is lightweight and works perfectly fine on Android too. For your particular case, you might be able to go parsing the string yourself, but as I assume this is not going to be the only place you need to parse json, the library might help you. Here is my suggestion:

Declare a class to which the json will be deserialzied:

import com.google.gson.annotations.SerializedName;
public class Story {
    @SerializedName(story_name)
    private String storyName;
}

And then deserialize your string to this class:

Gson gson = new Gson();
Story [] stories = gson.fromJson(is, Story[].class);

From then on you can iterate over this object array and use it however you like.

Couple of notes:

  • The '\n' is written \n not /n.
  • The logging is absolute requirement to know if you are coding for Android. Basically you just write Log.i("Log tag", "My first log message"); the Log is a class that android provides you (you still will need to import it of course). i is the log level you can choose between e(error), w(warning), i(info), d(debug), v(verbose). Log tag is just a string, basically you can place whatever you like there - I would suggest the class Name. Finally when this line is executed you will see in your LogCat My first log message. Logging is very useful to detect problems in the cod,e because you can display variable values at certain points of your program.

Upvotes: 1

Related Questions