2013-05-27 86 views
-2

我想通过http响应中的post方法将数据从我们的android应用程序传递到网站。如何将数据从android发送(发布)到网站或服务器

我现在想要的是 - 我给一个添加按钮,如果我点击添加它会打开一个编辑活动,它具有编辑文本和保存按钮,键入一些数据或文本,然后单击保存按钮它必须去该网站,我不再需要数据库也从我们的应用程序发送或发布数据在网站上。

Mainactivity.java

public class MainActivity extends ListActivity implements FetchDataListener 
{ 
    private static final int ACTIVITY_CREATE=0; 
    private ProgressDialog dialog; 
    private ProjectsDbAdapter mDbHelper; 
    private SimpleCursorAdapter dataAdapter; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 

     //setContentView(R.layout.activity_list_item); 
     mDbHelper = new ProjectsDbAdapter(this); 
      mDbHelper.open(); 
      //fillData(); 
      //registerForContextMenu(getListView()); 
     initView(); 
    } 



    private void initView() 
    { 
     // show progress dialog 
     dialog = ProgressDialog.show(this, "", "Loading..."); 
     String url = "http://floating-wildwood-1154.herokuapp.com/posts.json"; 
     FetchDataTask task = new FetchDataTask(this); 
     task.execute(url); 

     mDbHelper.open(); 
     Cursor projectsCursor = mDbHelper.fetchAllProjects(); 
     //startManagingCursor(projectsCursor); 

     // Create an array to specify the fields we want to display in the list (only TITLE) 
     String[] from = new String[]{ProjectsDbAdapter.KEY_TITLE}; 

     // and an array of the fields we want to bind those fields to (in this case just text1) 
     int[] to = new int[]{R.id.text1}; 

     /* Now create a simple cursor adapter and set it to display 
     SimpleCursorAdapter projects = 
       new SimpleCursorAdapter(this, R.layout.activity_row, projectsCursor, from, to); 
     setListAdapter(projects); 
     */ 
     // create the adapter using the cursor pointing to the desired data 
     //as well as the layout information 
     dataAdapter = new SimpleCursorAdapter(
      this, R.layout.activity_row, 
      projectsCursor, 
      from, 
      to, 
      0); 
     setListAdapter(dataAdapter); 

    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     //getMenuInflater().inflate(R.menu.activity_main, menu); 
     super.onCreateOptionsMenu(menu); 
     MenuInflater mi = getMenuInflater(); 
      mi.inflate(R.menu.activity_main, menu); 
     return true; 

    } 

    @Override 
     public boolean onMenuItemSelected(int featureId, MenuItem item) { 

       createProject(); 

      return super.onMenuItemSelected(featureId, item); 
    } 

    private void createProject() { 
      Intent i = new Intent(this, ProjectEditActivity.class); 
      startActivityForResult(i, ACTIVITY_CREATE); 
     } 

    @Override 
     protected void onActivityResult(int requestCode, int resultCode, Intent intent) { 
      super.onActivityResult(requestCode, resultCode, intent); 
      initView(); 
     } 

    @Override 
    public void onFetchComplete(List<Application> data) 
    { 
     // dismiss the progress dialog 
     if (dialog != null) 
      dialog.dismiss(); 
     // create new adapter 
     ApplicationAdapter adapter = new ApplicationAdapter(this, data); 
     // set the adapter to list 
     setListAdapter(adapter); 
    } 

    @Override 
    public void onFetchFailure(String msg) 
    { 
     // dismiss the progress dialog 
     if (dialog != null) 
      dialog.dismiss(); 
     // show failure message 
     Toast.makeText(this, msg, Toast.LENGTH_LONG).show(); 
    } 
} 

projecteditactivity.java

public class ProjectEditActivity extends Activity { 
    private EditText mTitleText; 
    private Button mConfirmButton; 
    private Long mRowId; 
    private ProjectsDbAdapter mDbHelper; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 

     super.onCreate(savedInstanceState); 
     mDbHelper = new ProjectsDbAdapter(this); 
     setContentView(R.layout.activity_project_edit); 

     mTitleText = (EditText) findViewById(R.id.title); 
     mConfirmButton = (Button) findViewById(R.id.confirm); 

     mRowId = savedInstanceState != null ? savedInstanceState.getLong(ProjectsDbAdapter.KEY_ROWID) 
              : null; 
     registerButtonListenersAndSetDefaultText(); 
    } 
    private void setRowIdFromIntent() { 
     if (mRowId == null || mRowId.longValue() == 0) { 
      Bundle extras = getIntent().getExtras();    
      mRowId = extras != null ? extras.getLong(ProjectsDbAdapter.KEY_ROWID) 
            : null; 

     } 
    } 

    @Override 
     protected void onPause() { 
      super.onPause(); 
      mDbHelper.close(); 
     } 
    @Override 
     protected void onResume() { 
      super.onResume(); 
      mDbHelper.open(); 
      setRowIdFromIntent(); 
      populateFields(); 
     } 

    private void registerButtonListenersAndSetDefaultText() { 
     mConfirmButton.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View view) { 
        saveState(); 
        setResult(RESULT_OK); 
        Toast.makeText(ProjectEditActivity.this, getString(R.string.task_saved_message), Toast.LENGTH_SHORT).show(); 
        finish(); 
       } 

      }); 
    } 
    private void populateFields() { 
     if (mRowId != null) { 
       Cursor Project = mDbHelper.fetchProject(mRowId); 
       startManagingCursor(Project); 
       mTitleText.setText(Project.getString(
         Project.getColumnIndexOrThrow(ProjectsDbAdapter.KEY_TITLE))); 
       Project.close(); 
     } 
       else { 
        // This is a new task - add defaults from preferences if set. 
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); 
        String defaultTitleKey = getString(R.string.pref_task_title_key); 
        String defaultTitle = prefs.getString(defaultTitleKey, null); 
        if(defaultTitle != null) 
        mTitleText.setText(defaultTitle); 
       } 

    } 

     @Override 
      protected void onSaveInstanceState(Bundle outState) { 
       super.onSaveInstanceState(outState); 
       outState.putLong(ProjectsDbAdapter.KEY_ROWID, mRowId); 
      } 

     private void saveState() { 
      String title = mTitleText.getText().toString(); 
      //if (mRowId == null) 
      if (mRowId == null || mRowId.longValue() == 0) 
      { 

       long id = mDbHelper.createProject(title); 
       if (id > 0) { 
        mRowId = id; 
         } 
        } else { 
          mDbHelper.updateProject(mRowId, title); 
         } 


        } 

    } 

这里我使用分贝,但我不希望我的应用程序使用的数据库,什么都我打字在编辑文本和点击保存按钮后,它必须传递或发送数据到服务器,我怎么能在我的应用程序中做到这一点。

+0

尝试搜索如何在谷歌发送服务器上的数据。这会给你很多链接。 –

+0

你可以得到我的要求@ChintanRathod,如何在我的代码中做一个兄弟,而不使用db –

回答

1

要发送DATAS到一个网站,你可以尝试致电点击收听此功能:

protected void sendDatas() { 
    mRegisterTask = new AsyncTask<Void, Void, Void>() { 

     @Override 
     protected Void doInBackground(Void... params) { 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost("YourURL"); 


      try { 
       // Add your data 
       List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);//Modify this number with the number of parameter you want to send 
       nameValuePairs.add(new BasicNameValuePair("PostParamName", "PostParamValue")); 
       httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

       // Execute HTTP Post Request 
       HttpResponse httpResponse = httpclient.execute(httppost); 
       // JSON parse 
       String response = EntityUtils.toString(httpResponse.getEntity()); 
       Log.i("httpResponse", response); 
            //do something with response if needed 

      } catch (ClientProtocolException e) { 
       Log.e("httpclient", "Error ClientProtocolException: " + e.getMessage()); 
      } catch (IOException e) { 
       Log.e("httpclient", "Error IOException: " + e.getMessage()); 
      } catch (JSONException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      return null; 
     } 

     @Override 
     protected void onPostExecute(Void result) { 
      mRegisterTask = null; 
     } 

    }; 
    mRegisterTask.execute(null, null, null); 

} 

声明mRegisterTask像AsyncTask<Void, Void, Void> mRegisterTask; 希望这有助于。

+0

我是一个新手,在我的代码中,我该怎么做才能编辑我的代码并告诉我,我不想使用数据库的一部分,只需在点击sava按钮后它必须发送@ Damien –

1

这里是一个发送POST到服务器的方法:

public String sendPostRequest(String url) { 
     String result = null; 
     URI wrapperUrl; 
     try { 
      wrapperUrl = new URI(url); 
      HttpParams httpParameters = new BasicHttpParams(); 
      int timeoutConnection = 20000; 
      HttpConnectionParams.setConnectionTimeout(httpParameters, 
       timeoutConnection); 
      // Set the default socket timeout (SO_TIMEOUT) 
      // in milliseconds which is the timeout for waiting for data. 
      int timeoutSocket = 20000; 
      HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); 
      HttpPost post = new HttpPost(wrapperUrl); 
      post.setParams(httpParameters); 
      HttpResponse response = getDefaultClient().execute(post); 
      HttpEntity responseEntity = response.getEntity(); 
      String result = EntityUtils.toString(responseEntity); 
      responseEntity.consumeContent(); 
      result = new JSONObject(jsonResultString); 
     } catch (URISyntaxException e) { 
      Logger.debug(TAG, "Exception: " + e.toString()); 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      Logger.debug(TAG, "Exception: " + e.toString()); 
      e.printStackTrace(); 
     } catch (IOException e) { 
      Logger.debug(TAG, "Exception: " + e.toString()); 
      e.printStackTrace(); 
     } 
     return result; 
    } 

提醒,使用它在工作线程:

private void registerButtonListenersAndSetDefaultText() { 
     mConfirmButton.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View view) { 
        saveState(); 
        sendQuestToServer(); 
        setResult(RESULT_OK); 
        Toast.makeText(ProjectEditActivity.this, getString(R.string.task_saved_message), Toast.LENGTH_SHORT).show(); 
        finish(); 
       } 

      }); 
    } 

private void sendQuestToServer() { 
    new Thread(new Runnale() { 
     @Override void run() { 
      String url = yourServerUrl + youreditText.getText.toString(); 
      sendQuestToServer(url); 
     } 
    }).start(); 
} 
+0

你可以编辑我的代码并告诉哥们,点击保存按钮后它必须去服务器部分 –

+0

,我该怎么做我的代码 –

+0

通知onClick(),我已经添加了基于你的代码的代码。 – buptcoder

0
Use the HttpClient or HttpPost; 
like this 
HttpPost post = new HttpPost(serverURL); 
     HttpResponse response = new DefaultHttpClient().execute(post); 
     int sCode = response.getStatusLine().getStatusCode(); 
     if (sCode == HttpStatus.SC_OK) { 
      return response.getEntity(); 
     } else 
      throw new Exception("StatusCode is " + sCode); 
+0

如何在我的代码中执行操作,而无需使用数据库,点击必须发送到服务器的保存按钮后 –

相关问题