Как передать значение и получить данные JSON в Android?

Я новичок в Android, я хочу получить данные JSON в моем устройстве. Но когда я пытаюсь передать значение, я получаю неизвестную ошибку в формате HTML. Даже я не использовал тег HTML в моем PHP-коде.

    public class Messages2 extends Activity {

private String[] navMenuTitles;
private TypedArray navMenuIcons;
private EditText editTextName;
SharedPreferences sp;
private String jsonResult;
private ListView listView;
private Button b;
EditText etname, et;
TextView tv;
String myJSON;

private static final String TAG_RESULTS="result";
private static final String TAG_USERNAME = "username";
private static final String TAG_NAME = "message_recd";
private static final String TAG_ADD ="message_sent";

JSONArray peoples = null;

ArrayList<HashMap<String, String>> personList;

ListView list;

public static final String USER_NAME = "USERNAME";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);

Intent intent = getIntent();
String fName = intent.getStringExtra("fname");



navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
// load icons from
// strings.xml



b=(Button)findViewById(R.id.Button01);
list = (ListView) findViewById(R.id.listView);
personList = new ArrayList<HashMap<String,String>>();


b.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {

Intent intent = getIntent();
String fName = intent.getStringExtra("fname");

getData(fName);

}
});
}


protected void showList(){
try {
JSONArray peoples = new JSONArray(myJSON);
HashMap<String,String> person = new HashMap<String,String>();
Intent intent1 = getIntent();
String fName = intent1.getStringExtra("fname");
person.put(TAG_NAME,fName);

for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String name=null, address=null;
if(c.has("message_recd"))
name = c.getString("message_recd");
else if(c.has("message_sent"))
address = c.getString("message_sent");

HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_NAME,name);
persons.put(TAG_ADD,address);
personList.add(persons);
}

ListAdapter adapter = new SimpleAdapter(
Messages2.this, personList, R.layout.list_item,
new String[]{TAG_NAME,TAG_ADD},
new int[]{R.id.name, R.id.address}
);

list.setAdapter(adapter);

} catch (JSONException e) {
Log.i("tagconvertstr", "["+myJSON+"]");
}
}

public void getData(String fName){
class GetDataJSON extends AsyncTask<String, Void, String>{

@Override
protected String doInBackground(String... params) {
String paramUsername = params[0];
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://10.0.2.2/progress_card/testing.php");

// Depends on your web service
httppost.setHeader("Content-type", "application/json");

InputStream inputStream = null;
String result = null;
try {
Intent intent1 = getIntent();
String fName = intent1.getStringExtra("fname");

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", fName));

HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();

inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();

String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.i("tagconvertstr", "["+result+"]");
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}

@Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute(fName);
}

}

Мой Логкат

09-24 06:44:09.973: I/tagconvertstr(3609): [<br />
09-24 06:44:09.973: I/tagconvertstr(3609): <font size='1'><table class='xdebug-error' dir='ltr' border='1' cellspacing='0' cellpadding='1'>
09-24 06:44:09.973: I/tagconvertstr(3609): <tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Notice: Undefined index: username in G:\wamp\www\progress_card\testing.php on line <i>7</i></th></tr>
09-24 06:44:09.973: I/tagconvertstr(3609): <tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>
09-24 06:44:09.973: I/tagconvertstr(3609): <tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>
09-24 06:44:09.973: I/tagconvertstr(3609): <tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0004</td><td bgcolor='#eeeeec' align='right'>382904</td><td bgcolor='#eeeeec'>{main}(  )</td><td title='G:\wamp\www\progress_card\testing.php' bgcolor='#eeeeec'>..\testing.php<b>:</b>0</td></tr>
09-24 06:44:09.973: I/tagconvertstr(3609): </table></font>
09-24 06:44:09.973: I/tagconvertstr(3609): [{"message_recd":""},{"message_recd":""},{"message_recd":""},{"message_recd":""},{"message_recd":""},{"message_recd":""},{"message_sent":""},{"message_sent":""},{"message_sent":""},{"message_sent":""},{"message_sent":""},{"message_sent":""}]
09-24 06:44:09.973: I/tagconvertstr(3609): ]

Мой php код

<?php
define('HOST','localhost');
define('USER','root');
define('PASS','');
define('DB','progress_card');
$con = mysqli_connect(HOST,USER,PASS,DB);
$username = $_POST['username'];
$sql1 = "select * from student_detail where parentusername='".$username."'";
$res1 = mysqli_query($con,$sql1);

$row1=mysqli_fetch_array($res1);

$cl=$row1['class']."-".$row1['section'];
$sql2="select * from teachers where classassign='$cl'";
$res2 = mysqli_query($con,$sql2);

$row2=mysqli_fetch_array($res2);

$to=$row2['email'];
$from=$row1['parentemail'];

$result = array();

$sql = "select * from messages where to_email='".$to."' and from_email='".$from."'";
$res = mysqli_query($con,$sql);

while($row = mysqli_fetch_array($res))
{
array_push($result,array('message_recd'=>$row['message']));
}

$sqlw = "select * from messages where from_email='".$to."' and to_email='".$from."'";
$resw = mysqli_query($con,$sqlw);

while($row5 = mysqli_fetch_array($resw))
{

array_push($result,array('message_sent'=>$row5['message']));
}
if(mysqli_query($con,$sql))
{
// echo 'success';
}
else
{
//echo 'failure';
}
//array_push($result,array('message_sent'=>"dfdsghdfgddfgdsd"));
//array_push($result,array('message_sent'=>"sfdsflkufhskfhdskjfsfssadfadsffsafasfsfsadfafsaf"));

//array_push($result,array('message_recd'=>$row1['parentemail'],'message_sent'=>$row2['email']));

echo json_encode($result);

mysqli_close($con);

?>

-1

Решение

Ваш URL должен возвращать только ответ JSON, иначе он не будет разбираться в Android.
Только эта часть должна быть возвращена в качестве ответа:

[{"message_recd":""},{"message_recd":""}]
1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector