gpt4 book ai didi

android - 使用 JSON 使用未弃用的方法将 MySQL 数据加载到 ListView 中

转载 作者:行者123 更新时间:2023-11-29 11:33:17 50 4
gpt4 key购买 nike

我需要将 mysql 数据库中的数据显示到 Android 应用程序中的 ListView 中。我在网上找到了一个教程,但有一些方法已被弃用(例如 HttpPost、HttpResponse、HttpClient 等)。我怎样才能找到替代方法?我要显示数据的这个Activity也是一个fragment。

这是我的代码:

public class PastOrders extends Fragment {

Activity context;

HttpPost httppost;

StringBuffer buffer;

HttpResponse response;

HttpClient httpclient;

ProgressDialog pd;

CustomerAdapter adapter;

ListView listProduct;

ArrayList<SingleOrder> records;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

View v = inflater.inflate(R.layout.past_orders, container, false);

context = this;

records = new ArrayList<SingleOrder>();

listProduct=(ListView)v.findViewById(R.id.listView1);

adapter=new CustomerAdapter(context, R.layout.list_order,R.id.pro_name,records);

listProduct.setAdapter(adapter);

return v;
}

public void onStart(){

super.onStart();

//execute background task

BackTask bt=new BackTask();

bt.execute();

}

private class BackTask extends AsyncTask<Void,Void,Void>{

protected void onPreExecute(){

super.onPreExecute();

pd = new ProgressDialog(context);

pd.setTitle("Retrieving data");

pd.setMessage("Please wait.");

pd.setCancelable(true);

pd.setIndeterminate(true);

pd.show();

}

protected Void doInBackground(Void...params){

InputStream is=null;

String result="";

try{

httpclient=new DefaultHttpClient();

httppost= new HttpPost("https://www.foodlebee.com/BeeTrack/orders.php");

response=httpclient.execute(httppost);

HttpEntity entity = response.getEntity();

// Get our response as a String.

is = entity.getContent();

}catch(Exception e){

if(pd!=null)

pd.dismiss(); //close the dialog if error occurs

Log.e("ERROR", e.getMessage());

}

try{

BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),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){

Log.e("ERROR", "Error converting result "+e.toString());

}

try{
result=result.substring(result.indexOf("["));

JSONArray jArray =new JSONArray(result);

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

JSONObject json_data =jArray.getJSONObject(i);

SingleOrder p=new SingleOrder();

p.setpName(json_data.getString("pname"));

p.setuPrice(json_data.getInt("uprice"));

records.add(p);

}

}

catch(Exception e){

Log.e("ERROR", "Error pasting data "+e.toString());

}

return null;

}

protected void onPostExecute(Void result){

if(pd!=null) pd.dismiss(); //close dialog

Log.e("size", records.size() + "");

adapter.notifyDataSetChanged(); //notify the ListView to get new records

}

}

}

这是我的 CustomAdapter 类,用于向 ListView 提供数据:

public class CustomAdapter extends ArrayAdapter<SingleOrder> {

int groupid;

ArrayList<SingleOrder> records;

Context context;


public CustomAdapter(Context context, int vg, int id, ArrayList<SingleOrder>
records) {

super(context, vg, id, records);

this.context = context;

groupid = vg;

this.records = records;

}

public View getView(int position, View convertView, ViewGroup parent) {


LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

View itemView = inflater.inflate(groupid, parent, false);

TextView textName = (TextView) itemView.findViewById(R.id.pro_name);

textName.setText(records.get(position).getpName());

TextView textPrice = (TextView) itemView.findViewById(R.id.pro_uprice);

textPrice.setText(records.get(position).getuPrice() + "$");


return itemView;

}

}

这是我的 SingleOrder 类:

public class SingleOrder {

private String pName;

private int uPrice;

public void setpName(String pName){this.pName=pName;}

public void setuPrice(int uPrice){this.uPrice=uPrice;}

public String getpName(){return pName;}

public int getuPrice(){return uPrice;}

}

我遇到错误:

context = this; 

我应该使用“context = getActivity();” ?

在下面几行中,我使用了已弃用的方法:

            httpclient=new DefaultHttpClient();

httppost= new HttpPost("https://www.example.com/orders.php");

response=httpclient.execute(httppost);

HttpEntity entity = response.getEntity();

is = entity.getContent();

我是否也应该在最后一行中使用 getActivity()

最佳答案

您可以使用 Android API 本身提供的类。

String path, response;
URL url;
HttpURLConnection conn;
int responseCode;
try
{
response = "";
//path is the URL to connect with
path = "http://api.openweathermap.org/data/2.5/find?lat=55.5&lon=37.5&cnt=10"
url = new URL(path);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Connection", "close");
conn.setConnectTimeout(15000);
conn.connect();
responseCode = conn.getResponseCode();
Log.d("App Name", "Result Code: " + responseCode);
if (responseCode == HttpsURLConnection.HTTP_OK)
{
String line = "";
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is), 65535);
Log.d("Output", br.toString());
while ((line = br.readLine()) != null)
{
response += line;
Log.d("output lines", line);
}
is.close();
br.close();
}
else
{
conn.disconnect();
response = "";
}
}
catch (UnsupportedEncodingException | ProtocolException | MalformedURLException | IOException e)
{
Log.d("App Name",""+e.printStackTrace());
}
finally
{
Log.d("App Name"," Connection disconnected..");
conn.disconnect();
}

引用API:https://developer.android.com/reference/java/net/HttpURLConnection.html

说明:https://developer.android.com/training/basics/network-ops/connecting.html

关于android - 使用 JSON 使用未弃用的方法将 MySQL 数据加载到 ListView 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37039763/

50 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com