简体   繁体   中英

How to get a single column in android mysql

How can i get a single column using using android. instead of getting everything from the database. i want to get only the column where full_name="john".

DataParser.jave

public class DataParser  extends AsyncTask<Void,Void,Integer>{

Context c;
ListView lv;
String jsonData;

ProgressDialog pd;
ArrayList<Person> persons=new ArrayList<>();

public DataParser(Context c, ListView lv, String jsonData) {
    this.c = c;
    this.lv = lv;
    this.jsonData = jsonData;
}

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

    pd=new ProgressDialog(c);
    pd.setTitle("Parse");
    pd.setMessage("Parsing...Please wait");
    pd.show();
}

@Override
protected Integer doInBackground(Void... params) {
    return this.parseData();
}

@Override
protected void onPostExecute(Integer result) {
    super.onPostExecute(result);

    pd.dismiss();
    if(result==0)
    {
        Toast.makeText(c,"Unable to parse",Toast.LENGTH_SHORT).show();
    }else {
        //CALL ADAPTER TO BIND DATA
        CustomAdapter adapter=new CustomAdapter(c,persons);
        lv.setAdapter(adapter);
    }
}



private int parseData()
{
    try {
        JSONArray ja=new JSONArray(jsonData);
        JSONObject jo=null;

        persons.clear();
        Person s=null;




        for(int i=0;i<ja.length();i++) {


            jo = ja.getJSONObject(i);


            int id = jo.getInt("id");
            String name = jo.getString("full_name");
            String sex = jo.getString("sex");
            String location = jo.getString("location");


            s = new Person();
            s.setId(id);
            s.setFull_name(name);
            s.setSex(sex);
            s.setLocation(location);


            persons.add(s);



        }

                return 1;




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

    return 0;
}

}

Downloader.java

public class Downloader extends AsyncTask<Void,Void,String> {

Context c;
String urlAddress;
ListView lv;

ProgressDialog pd;

public Downloader(Context c, String urlAddress, ListView lv) {
    this.c = c;
    this.urlAddress = urlAddress;
    this.lv = lv;
}

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

    pd=new ProgressDialog(c);
    pd.setTitle("Fetch");
    pd.setMessage("Fetching....Please wait");
    pd.show();
}

@Override
protected String doInBackground(Void... params) {
    return this.downloadData();
}


@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);

    pd.dismiss();

    if(s==null)
    {
        Toast.makeText(c,"Unsuccessfull,Null 
    returned",Toast.LENGTH_SHORT).show();
    }else
    { 
        //CALL DATA PARSER TO PARSE
        DataParser parser=new DataParser(c,lv,s);
        parser.execute();

    }


}


private String downloadData()
{
    HttpURLConnection con=Connector.connect(urlAddress);
    if(con==null)
    {
        return null;
    }

    InputStream is=null;
    try {

        is=new BufferedInputStream(con.getInputStream());
        BufferedReader br=new BufferedReader(new InputStreamReader(is));

        String line=null;
        StringBuffer response=new StringBuffer();

        if(br != null)
        {
            while ((line=br.readLine()) != null)
            {
                response.append(line+"\n");
            }

            br.close();

        }else
        {
            return null;
        }

        return response.toString();

    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if(is != null)
        {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    return null;
  }
 }

Connector.java

public class Connector {

public static HttpURLConnection connect(String urlAddress)
{
    try {
        URL url=new URL(urlAddress);
        HttpURLConnection con= (HttpURLConnection) url.openConnection();

        //SET PROPS
        con.setRequestMethod("GET");
        con.setConnectTimeout(20000);
        con.setReadTimeout(20000);
        con.setDoInput(true);

        return con;

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}


  }

Person.java

public class Person {
    int id;
String full_name, sex, location;

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getFull_name() {
    return full_name;
}

public void setFull_name(String full_name) {
    this.full_name = full_name;
}

public String getSex() {
    return sex;
}

public void setSex(String sex) {
    this.sex = sex;
}

public String getLocation() {
    return location;
}

public void setLocation(String location) {
    this.location = location;
}

}

CustomAdapter.java

public class CustomAdapter extends BaseAdapter {

Context c;
ArrayList<Person> persons;
LayoutInflater inflater;

public CustomAdapter(Context c, ArrayList<Person> persons) {
    this.c = c;
    this.persons = persons;

    //INITIALIE
    inflater= (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
    return persons.size();
}

@Override
public Object getItem(int position) {
    return persons.get(position);
}

@Override
public long getItemId(int position) {
    return persons.get(position).getId();
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    if(convertView==null)
    {
        convertView=inflater.inflate(R.layout.model,parent,false);
    }

    TextView nameTxt= (TextView) convertView.findViewById(R.id.nameTxt);
    TextView sexTxt= (TextView) convertView.findViewById(R.id.propellantTxt);
    TextView locationTxt= (TextView) convertView.findViewById(R.id.descTxt);

    nameTxt.setText(persons.get(position).getFull_name());
    sexTxt.setText(persons.get(position).getSex());
    locationTxt.setText(persons.get(position).getLocation());

    //ITEM CLICKS
    convertView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(c,persons.get(position).getFull_name(),Toast.LENGTH_SHORT).show();
        }
    });

    return convertView;
}

}

server side php file

<?php 

$host = 'localhost';
$username='root';
$pwd ='';
$db ='user';

$con=mysqli_connect($host,$username,$pwd,$db) or die('Unable to connect');
if(mysqli_connect_error($con))
{
echo "Failed to Connect to Database ".mysqli_connect_error();
}

$query=mysqli_query($con,"SELECT * FROM person");
if($query)
{
 while($row=mysqli_fetch_array($query))
{
$data[]=$row;
}
 print(json_encode($data));
}else
{
echo('Not Found ');
 }
 mysqli_close($con);
 ?>

mainactivity.java

public class MainActivity extends AppCompatActivity {

String urlAddress="http://localhost/Android/includes/retrive.php";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    final ListView lv= (ListView) findViewById(R.id.lv);



    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Downloader d=new Downloader(MainActivity.this,urlAddress,lv);
            d.execute();
        }
    });
}

}

Got the code online and cant find a way to get a single column

It looks like the json you are using is from an API response. In that case, if you want to do it in SQL you would need to create a new api and SQL query on the server. If you want to just limit what is displaying in the loop, only parse the parts you want.

for(int i=0;i<ja.length();i++) {


        jo = ja.getJSONObject(i);


        int id = jo.getInt("id");
        String name = jo.getString("full_name");

        s = new Person();
        s.setFull_name(name);

        persons.add(s);



    }

You would then need to also change the logic in your activity that displays the data, and only display person.name, as the rest of the properties will be null.

I recommend doing more research on consuming APIs and parsing JSON, as it appears that the code you are using does not have a database or SQL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM