【问题标题】:display the recently inserted record into MySQL database in next android activity for editing purpose在下一个 android 活动中显示最近插入 MySQL 数据库的记录以进行编辑
【发布时间】:2017-11-06 06:36:44
【问题描述】:

下面是从 android 活动将数据插入 MySQL 数据库的代码。现在,我想在下一个活动的编辑文本和微调器字段中显示最近插入的数据。我迫切需要一个解决方案,如果您不清楚我的问题,请提出问题。我使用 stackoverflow 作为我最后的手段。

insertbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            getDatafromForm();
            SendDataToServer(opened,closed,site,tech,own,status,category,affected_kpis,bsc,grid,cells,priority,ana,recom,alarm,receiver,carboncopy);
        }
    });
}

public void getDatafromForm(){
    opened=date_opened.getText().toString();
    closed=date_closed.getText().toString();
    site=sit.getText().toString();
    tech=tech_spinner.getSelectedItem().toString();
    own=owner.getSelectedItem().toString();
    status=status_spinner.getSelectedItem().toString();
    category=category_spinner.getSelectedItem().toString();
    affected_kpis=kpis.getText().toString();
    bsc=rnc.getText().toString();
    grid=grid_spinner.getSelectedItem().toString();
    cells=affected_cells.getText().toString();
    priority=priority_spinner.getSelectedItem().toString();
    ana=analysis.getText().toString();
    recom=recommendations.getText().toString();
    alarm=alarms.getText().toString();
    receiver=to.getText().toString();
    carboncopy=cc.getText().toString();
}

public void SendDataToServer(final String dateopened,final String dateclosed,final String site,final String tech,
                             final String own,
                             final String status,final String category, final String affected_kpis,final String bsc,
                             final String grid,final String cells,final String priority,
                             final String ana,final String recom,final String alarm,final String receiver,
                             final String carboncopy ){
    class SendPostReqAsyncTask extends AsyncTask<Object, Object, String> {

        @Override
        protected String doInBackground(Object... params) {
            String quickdo=dateopened;
            String quickdc=dateclosed;
            String quicksite=site;
            String quicktech=tech;
            String quickowner=own;
            String quickstatus=status;
            String quickcategory=category;
            String quickaffected_kpis=affected_kpis;
            String quickbsc=bsc;
            String quickgrid=grid;
            String quickcells=cells;
            String quickpriority=priority;
            String quickanalysis=ana;
            String quickrecom=recom;
            String quickalarm=alarm;
            String quickreceiver=receiver;
            String quickcarboncopy=carboncopy;

            List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("date_opened",quickdo));
            nameValuePairs.add(new BasicNameValuePair("date_closed",quickdc));
            nameValuePairs.add(new BasicNameValuePair("site",quicksite));
            nameValuePairs.add(new BasicNameValuePair("technology",quicktech));
            nameValuePairs.add(new BasicNameValuePair("owner",quickowner));
            nameValuePairs.add(new BasicNameValuePair("status",quickstatus));
            nameValuePairs.add(new BasicNameValuePair("category",quickcategory));
            nameValuePairs.add(new BasicNameValuePair("affected_kpis",quickaffected_kpis));
            nameValuePairs.add(new BasicNameValuePair("bsc_rnc",quickbsc));
            nameValuePairs.add(new BasicNameValuePair("grid",quickgrid));
            nameValuePairs.add(new BasicNameValuePair("affected_cells",quickcells));
            nameValuePairs.add(new BasicNameValuePair("priority",quickpriority));
            nameValuePairs.add(new BasicNameValuePair("analysis",quickanalysis));
            nameValuePairs.add(new BasicNameValuePair("recommendations",quickrecom));
            nameValuePairs.add(new BasicNameValuePair("alarm",quickalarm));
            nameValuePairs.add(new BasicNameValuePair("receiver",quickreceiver));
            nameValuePairs.add(new BasicNameValuePair("carboncopy",quickcarboncopy));



            HttpClient httpClient=new DefaultHttpClient();
            HttpPost httpPost=new HttpPost(insert_url);
            try {
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse httpResponse=httpClient.execute(httpPost);
                HttpEntity entity=httpResponse.getEntity();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
              catch (IOException e) {
                e.printStackTrace();
            }
           // JSONObject myobject=myparser.getJSONFromUrl(insert_url);
            return "Successfull";
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            Toast.makeText(createRecord.this,"Data successfully submitted",Toast.LENGTH_LONG).show();
            //pass json object result with the intent here
           /* Intent i=new Intent(createRecord.this,EditActivity.class);
            i.putExtra("data",result.toString());
            startActivity(i); */
        }
    }
    SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
    sendPostReqAsyncTask.execute(dateopened,dateclosed,site,tech,own,status,category,affected_kpis,bsc,grid,cells,priority,
            ana,recom,alarm,receiver,carboncopy );


}

我的php脚本是:

   <?php
include "connect.php";

//extract($_POST);


$date_opened=$_POST['date_opened'];
$date_closed=$_POST['date_closed'];
$site=$_POST['site'];
$technology=$_POST['technology'];
$owner=$_POST['owner'];
$status=$_POST['status'];
$category=$_POST['category'];
$affected_kpis=$_POST['affected_kpis'];
$bsc_rnc=$_POST['bsc_rnc'];
$grid=$_POST['grid'];
$affected_cells=$_POST['affected_cells'];
$priority=$_POST['priority'];
$analysis=$_POST['analysis'];
$recommendations=$_POST['recommendations'];
$alarms=$_POST['alarm'];
$receiver=$_POST['receiver'];
$carboncopy=$_POST['carboncopy'];
$age;

$rec="SELECT COUNT(grid) as total from data where grid='$grid'";

$result = mysqli_query($conn,$rec);
$row = mysqli_fetch_array($result);

$total = $row['total'];


if(strtotime($date_closed)=='0'){
    $age=0;
}
else{
$difference=strtotime($date_closed) - strtotime($date_opened);
$age= floor($difference/(60 * 60* 24));
}



$sql = "INSERT into data set 
        date_opened = '$date_opened',
        date_closed = '$date_closed',
        aging='$age',
        site = '$site',
        technology='$technology',
        owner = '$owner',
        status = '$status',
        category = '$category',
        affected_kpis = '$affected_kpis',
        bsc_rnc = '$bsc_rnc',
        grid = '$grid',
        recurrence='$total',
        affected_cells = '$affected_cells',
        priority = '$priority',
        analysis = '$analysis',
        recommendations = '$recommendations',
        alarm = '$alarms',
        receiver='$receiver',
        carboncopy='$carboncopy'

";


if ($conn->query($sql) === TRUE) {
    $last_id = $conn->insert_id;
    $json= array('id'=>$last_id,'date_opened'=>$date_opened,'date_closed'=>$date_closed,'aging'=>$age,'site'=>$site,
                'technology'=>$technology,'owner'=>$owner,'status'=>$status,'category'=>$category,
                 'affected_kpis'=>$affected_kpis,'bsc_rnc'=>$bsc_rnc,'grid'=>$grid,'recurrence'=>$total,
                'affected_cells'=>$affected_cells,'priority'=>$priority,'analysis'=>$analysis,
                 'recommendations'=>$recommendations,'alarm'=>$alarms,'receiver'=>$receiver,'carboncopy'=>$carboncopy);

    //echo 'Data Inserted Successfully';
    echo json_encode($json);
}
else {
    echo "Try Again " . $sql . "<br>" . $conn->error;
}


?>

【问题讨论】:

    标签: php android mysql json


    【解决方案1】:

    您可以创建自定义 pojo 类并为其设置最近的插入数据。然后将 pojo 类传递给下一个活动。

    喜欢,创建 pojo 类并设置所有值。

    public class Test implements Serializable {
    String opened, closed;
    
    public Test(String opened, String closed) {
        this.opened = opened;
        this.closed = closed;
    }
    
    public String getOpened() {
        return opened;
    }
    
    public void setOpened(String opened) {
        this.opened = opened;
    }
    
    public String getClosed() {
        return closed;
    }
    
    public void setClosed(String closed) {
        this.closed = closed;
    }
    

    }

    Test test = new Test(date_opened.getText().toString(), 
    date_closed.getText().toString());
    
    Intent intent = new Intent(createRecord.this,EditActivity.class);
    intent.putExtra("data",test);
    startActivity(intent); 
    

    你可以得到类似的数据,

     Test test = (Test) getIntent().getSerializableExtra("data");
     test.getClosed() // for get closed value
     etc..
    

    首先,您必须从 api 获取作为字符串的响应,然后才能转换为 JSON 对象。 你可以得到这样的回应。

     static String json = "";
     static InputStream is = null;
    
     DefaultHttpClient httpClient = new DefaultHttpClient();
     HttpPost httpPost = new HttpPost(url);
     httpPost.setEntity(new UrlEncodedFormEntity(params));
    
     HttpResponse httpResponse = httpClient.execute(httpPost);
     HttpEntity httpEntity = httpResponse.getEntity();
     is = httpEntity.getContent();
    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();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
    

    现在,您可以将响应转换为 JSON 对象,或者您也可以通过 GSON 库进行。

    【讨论】:

    • 如何更新数据库中之前插入的数据?
    • 您必须为其保留 id,然后您可以在该 id 的位置触发更新查询。
    • id 字段在数据库中自动递增我如何在我的 android 应用程序中获取它...我的主要问题是我无法从数据库中获取数据以显示在下一个活动的各个字段中。
    • 你能发布从 SendPostReqAsyncTask 得到的响应吗?
    • 另外,请查看此链接androidhive.info/2012/05/how-to-connect-android-with-php-mysql,可能会对您有所帮助。
    【解决方案2】:
     class CreateNewData extends AsyncTask<Object, Object, JSONObject> {
        String opened=date_opened.getText().toString();
        String closed=date_closed.getText().toString();
        String site=sit.getText().toString();
        String tech=tech_spinner.getSelectedItem().toString();
        String own=owner.getSelectedItem().toString();
        String status=status_spinner.getSelectedItem().toString();
        String category=category_spinner.getSelectedItem().toString();
        String affected_kpis=kpis.getText().toString();
        String bsc=rnc.getText().toString();
        String grid=grid_spinner.getSelectedItem().toString();
        String cells=affected_cells.getText().toString();
        String priority=priority_spinner.getSelectedItem().toString();
        String ana=analysis.getText().toString();
        String recom=recommendations.getText().toString();
        String alarm=alarms.getText().toString();
        String receiver=to.getText().toString();
        String carboncopy=cc.getText().toString();
    
        @Override
        protected JSONObject doInBackground(Object... params) {
    
            List<NameValuePair> param=new ArrayList<NameValuePair>();
            param.add(new BasicNameValuePair("date_opened",opened));
            param.add(new BasicNameValuePair("date_closed",closed));
            param.add(new BasicNameValuePair("site",site));
            param.add(new BasicNameValuePair("technology",tech));
            param.add(new BasicNameValuePair("owner",own));
            param.add(new BasicNameValuePair("status",status));
            param.add(new BasicNameValuePair("category",category));
            param.add(new BasicNameValuePair("affected_kpis",affected_kpis));
            param.add(new BasicNameValuePair("bsc_rnc",bsc));
            param.add(new BasicNameValuePair("grid",grid));
            param.add(new BasicNameValuePair("affected_cells",cells));
            param.add(new BasicNameValuePair("priority",priority));
            param.add(new BasicNameValuePair("analysis",ana));
            param.add(new BasicNameValuePair("recommendations",recom));
            param.add(new BasicNameValuePair("alarm",alarm));
            param.add(new BasicNameValuePair("receiver",receiver));
            param.add(new BasicNameValuePair("carboncopy",carboncopy));
    
            JSONObject json=jsonParser.makeHttpRequest(insert_url,"POST",param);
            Log.d("Create Response", json.toString());
    
    
    
    
    
            return json;
        }
    
        @Override
        protected void onPostExecute(JSONObject json) {
            super.onPostExecute(json);
            try {
                int id=json.getInt("id");
    
                if(id==0){
                    Toast.makeText(createRecord.this,json.getString("message"),Toast.LENGTH_LONG).show();
                    //Toast.makeText(createRecord.this,"Data Not Inserted",Toast.LENGTH_LONG).show();
    
                }
                else{
                    Toast.makeText(createRecord.this,json.getString("message"),Toast.LENGTH_LONG).show();
                    Intent i=new Intent(createRecord.this,EditActivity.class);
                    //passing data as json object to next activity
                    i.putExtra("data",json.toString());
                    startActivity(i);
                    finish();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    

    而PHP代码会是这样的:

        if ($conn->query($sql) === TRUE) {
        $last_id = $conn->insert_id;
        $json['id']=$last_id;
        $json['date_opened']=$date_opened;
        $json['date_closed']=$date_closed;
        $json['site']=$site;
        $json['technology']=$technology;
        $json['owner']=$owner;
        $json['status']=$status;
        $json['category']=$category;
        $json['affected_kpis']=$affected_kpis;
        $json['bsc_rnc']=$bsc_rnc;
        $json['grid']=$grid;
        $json['affected_cells']=$affected_cells;
        $json['priority']=$priority;
        $json['analysis']=$analysis;
        $json['recommendations']=$recommendatons;
        $json['alarm']=$alarms;
        $json['receiver']=$receiver;
        $json['carboncopy']=$carboncopy;
        $json['message']="Data inserted successfully";
        echo json_encode($json);
        //echo 'Data Inserted Successfully';
        echo json_encode($json);
    }
    
        else {
            $json['id']=0;
            $json['message']="Data not inserted";
            echo json_encode($json);}
        ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-06
      • 1970-01-01
      • 2015-12-04
      • 2019-04-29
      • 1970-01-01
      • 1970-01-01
      • 2019-01-05
      • 1970-01-01
      相关资源
      最近更新 更多