duanbai1974 2016-08-13 10:59
浏览 127

从json中的数据库中读取数据

i write a program that want to read some data from database,it show all the data that is exist in Saturday table that i created in my database, but i want use clause to show some data. actually in this program i want show the data just for each person that login and his name is in the String that i call whoo(look at android code); how can change it to read just data that is related to person that login. in my table is a row that i called it user_name, and in android code i have a String that called whoo, i want show the data with this clause: WHERE user_name = '$username' please help me... i write this program with PHP and json and here is my code:

php:

<?php


$con = mysql_connect("...","...","....");

mysql_select_db("...",$con);

$response=array();
$result=mysql_query("select * from saturday");

if(mysql_num_rows($result)>0){

$response["saturday"]=array();

while($row=mysql_fetch_array($result)){
    $temp=array();
    $temp["username"]=$row["user_name"];
    $temp["userside"]=$row["user_sideup"];
    $temp["userchair"]=$row["user_chair"];
    $temp["userjump"]=$row["user_jump"];
    $temp["userstep"]=$row["user_step"];
    $temp["usercalf"]=$row["user_calf"];



    array_push($response["saturday"],$temp);


}

$response["t"]=1;
echo json_encode($response);



}else{

$response["t"]=0;
$response["message"]="not fonud";
echo json_encode($response);

}


?>

and this is my android:

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class ResultPage extends ListActivity {

private ProgressDialog pd;
JSONParser jparser = new JSONParser();
ArrayList<HashMap<String, String>> P;



JSONArray s = null;
private static String url = "http://akosamanus.xzn.ir/getsaturday.php";

TextView who,which;


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



    who = (TextView)findViewById(R.id.who);
    which = (TextView)findViewById(R.id.which);


    Bundle extras = getIntent().getExtras();
    String whoo = extras.getString("uname");
    String whiche = extras.getString("uday");

    who.setText(whoo);
    which.setText(whiche);

    P = new ArrayList<HashMap<String, String>>();
    new result().execute();
}





@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    String zname = ((TextView) v.findViewById(R.id.tvsetname)).getText().toString();
    String zside = ((TextView) v.findViewById(R.id.tvsetside)).getText().toString();
    String zstep = ((TextView) v.findViewById(R.id.tvsetstep)).getText().toString();
    String zcalf = ((TextView) v.findViewById(R.id.tvsetcalf)).getText().toString();
    String zjump = ((TextView) v.findViewById(R.id.tvsetjump)).getText().toString();
    String zchair = ((TextView) v.findViewById(R.id.tvsetchair)).getText().toString();
    Intent intent = new Intent(ResultPage.this,CResultPage.class);

    intent.putExtra("zside",zside);
    intent.putExtra("zstep",zstep);
    intent.putExtra("zcalf",zcalf);
    intent.putExtra("zjump",zjump);
    intent.putExtra("zchair",zchair);
    startActivityForResult(intent,1);


}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK && requestCode==1){
        if(data.hasExtra("Result")){

        }
    }
}


class result extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pd = new ProgressDialog(ResultPage.this);
        pd.setMessage("loading...");
        pd.show();
    }


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



        // ContentValues params = new ContentValues();
        List<NameValuePair> params = new ArrayList<NameValuePair>(); // Building Parameters

        // getting JSON string from URL
        JSONObject json = jparser.makeHttpRequest(url, "GET", params);


        try {
            int t = json.getInt("t");

            if (t==1){
                s=json.getJSONArray("saturday");
                for (int i=0;i<s.length();i++){
                    JSONObject c=s.getJSONObject(i);
                    String username=c.getString("username");
                    String userside=c.getString("userside");
                    String userchair=c.getString("userchair");
                    String userjump=c.getString("userjump");
                    String userstep=c.getString("userstep");
                    String usercalf=c.getString("usercalf");
                    String today=which.getText().toString();


                    HashMap<String,String> map=new HashMap<String,String>();
                    map.put("username",username);
                    map.put("userside",userside);
                    map.put("userchair",userchair);
                    map.put("userjump",userjump);
                    map.put("userstep",userstep);
                    map.put("usercalf", usercalf);
                    map.put("Saturday", today);


                    P.add(map);



                }


            }else {
                Toast.makeText(ResultPage.this, "ooooooooooops", Toast.LENGTH_SHORT).show();
            }


        } catch (JSONException e) {
            e.printStackTrace();

        }


        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        pd.dismiss();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ListAdapter adapter=new SimpleAdapter(ResultPage.this,P,R.layout.item_list2,
                        new  String[]{"username","userside","userchair","userjump","userstep","usercalf","Saturday"},
                        new  int[]{R.id.tvsetname,R.id.tvsetside,R.id.tvsetchair,R.id.tvsetjump,R.id.tvsetstep
                                ,R.id.tvsetcalf,R.id.tvsetday});

                setListAdapter(adapter);




            }
        });

    }

}

}


08-14 13:14:11.433    4305-4305/com.example.eagle.start1 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.eagle.start1, PID: 4305
android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
        at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
        at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
        at java.net.InetAddress.getAllByName(InetAddress.java:215)
        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:365)
        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.eagle.start1.JSONParser.makeHttpRequest(JSONParser.java:118)
        at com.example.eagle.start1.ResultPage$result$1.run(ResultPage.java:135)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
  • 写回答

1条回答 默认 最新

  • dragon87836215 2016-08-13 12:19
    关注

    For Getting Specific Value from database we have to use GET or POST method so here i have modified your code for PHP (using GET method).

    <?php
        $con = mysql_connect("...","...","....");
    
        mysql_select_db("...",$con);
    
        if (isset($_GET["username"])) {
            $username = $_GET['username'];
    
        $response=array();
        $result=mysql_query("select * from saturday where user_name= $username");
    
        if(mysql_num_rows($result)>0){
    
        $response["saturday"]=array();
    
        while($row=mysql_fetch_array($result)){
            $temp=array();
            $temp["username"]=$row["user_name"];
            $temp["userside"]=$row["user_sideup"];
            $temp["userchair"]=$row["user_chair"];
            $temp["userjump"]=$row["user_jump"];
            $temp["userstep"]=$row["user_step"];
            $temp["usercalf"]=$row["user_calf"];
    
    
    
            array_push($response["saturday"],$temp);
    
    
        }
    
        $response["t"]=1;
        echo json_encode($response);
    
    
    
        }else{
    
        $response["t"]=0;
        $response["message"]="not fonud";
        echo json_encode($response);
    
        }
    
        }
        ?>
    

    And at Android side you have to pass user_name in NameValuePair like below

     List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username",who.getText()));
            final JSONObject json = jParser.makeHttpRequest(url, "GET", params);
    

    if you have any query just watch this or comment below :) Happy Coding!

    评论

报告相同问题?

悬赏问题

  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试