duanfan8360 2013-05-07 12:23
浏览 59

Android - 客户端服务器,发布请求

Situation :

I am working on Client-Server Communication.

When the users save the data (name of product, image, note), it should be transferred to the server side of the database.

But, I don't know how to code http Post request on the client side(Android).

MyWishlistsActivity.java

public class MyWishlistsActivity extends ListActivity {


SQLiteConnector sqlCon;
private CustomWishlistsAdapter custAdapter;

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

    String[] from = new String[] { Wishlists.NAME, Wishlists.NOTE };
    int[] to = new int[] { R.id.name };
    custAdapter = new CustomWishlistsAdapter(this,R.layout.wishlist_list_item, null, from, to);
    this.setListAdapter(custAdapter);   

}

@Override
protected void onResume() {
    super.onResume();
    new GetContacts().execute((Object[]) null);
}

@SuppressWarnings("deprecation")
@Override
protected void onStop() {
    Cursor cursor = custAdapter.getCursor();

    if (cursor != null)
        cursor.deactivate();

    custAdapter.changeCursor(null);
    super.onStop();

}

private class GetContacts extends AsyncTask<Object, Object, Cursor> {
    SQLiteConnector dbConnector = new SQLiteConnector(MyWishlistsActivity.this);

    @Override
    protected Cursor doInBackground(Object... params) {
        return dbConnector.getAllWishlists();  
    }

    @Override
    protected void onPostExecute(Cursor result) {
        custAdapter.changeCursor(result);
        }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Intent addWishlists = new Intent(MyWishlistsActivity.this,AddEditWishlists.class);
    startActivity(addWishlists);
    //Client-Server
    Intent addWishlists2 = new Intent(MyWishlistsActivity.this,Server_AddWishlists.class);
    startActivity(addWishlists2);
    //Client-Server End
    return super.onOptionsItemSelected(item);
 }  
}

AddWishlists.java

public class AddEditWishlists extends Activity {


private EditText inputname;
private EditText inputnote;
private Button upload;
private Bitmap yourSelectedImage;
private ImageView inputphoto;
private Button save;
private int id;
private byte[] blob=null;
byte[] image=null;

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

private void setUpViews() {

    inputname = (EditText) findViewById(R.id.inputname);
    inputnote = (EditText) findViewById(R.id.inputnote);
    inputphoto = (ImageView) findViewById(R.id.inputphoto); 

    Bundle extras = getIntent().getExtras();

    if (extras != null) {
        id=extras.getInt("id");
        inputname.setText(extras.getString("name"));
        inputnote.setText(extras.getString("note"));
        image = extras.getByteArray("blob");

        if (image != null) {
            if (image.length > 3) {
                inputphoto.setImageBitmap(BitmapFactory.decodeByteArray(image,0,image.length));
            }
        }

    }




    upload = (Button) findViewById(R.id.upload);
    upload.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            startActivityForResult(intent, 0);
        }
    });

    save = (Button) findViewById(R.id.save);
    save.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            if (inputname.getText().length() != 0) {
                AsyncTask<Object, Object, Object> saveContactTask = new AsyncTask<Object, Object, Object>() {
                    @Override
                    protected Object doInBackground(Object... params) {
                        saveContact();
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Object result) {
                        finish();
                    }
                };

                saveContactTask.execute((Object[]) null);
            } else {
                AlertDialog.Builder alert = new AlertDialog.Builder(
                        AddEditWishlists.this);
                alert.setTitle("Error In Save Wish List");
                alert.setMessage("You need to Enter Name of the Product");
                alert.setPositiveButton("OK", null);
                alert.show();
            }
        }
    });
}

private void saveContact() {

    if(yourSelectedImage!=null){
        ByteArrayOutputStream outStr = new ByteArrayOutputStream();
        yourSelectedImage.compress(CompressFormat.JPEG, 100, outStr);
        blob = outStr.toByteArray();
    }

    else{blob=image;}

    SQLiteConnector sqlCon = new SQLiteConnector(this);

    if (getIntent().getExtras() == null) {
        sqlCon.insertWishlist(inputname.getText().toString(), inputnote.getText().toString(), blob);
    }

    else {
        sqlCon.updateWishlist(id, inputname.getText().toString(), inputnote.getText().toString(),blob);
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode,Intent resultdata) {
    super.onActivityResult(requestCode, resultCode, resultdata);
    switch (requestCode) {
    case 0:
        if (resultCode == RESULT_OK) {
            Uri selectedImage = resultdata.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);

            cursor.close();
            // Convert file path into bitmap image using below line.
            yourSelectedImage = BitmapFactory.decodeFile(filePath);
            inputphoto.setImageBitmap(yourSelectedImage);
        }

    }
}

}

ViewWishlist.java

public class ViewWishlist extends Activity {

private TextView name;
private TextView note;
private ImageView photo;
private Button backBtn;
private byte[] image;

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

private void setUpViews() {
    name = (TextView) findViewById(R.id.inputname);
    note = (TextView) findViewById(R.id.inputnote);
    photo = (ImageView) findViewById(R.id.inputphoto);


    Bundle extras = getIntent().getExtras();

    if (extras != null) {
        name.setText(extras.getString("name"));
        note.setText(extras.getString("note"));
        image = extras.getByteArray("blob");

        if (image != null) {
            if (image.length > 3) {
                photo.setImageBitmap(BitmapFactory.decodeByteArray(image,0,image.length));
            }
        }

    }

    backBtn=(Button)findViewById(R.id.back);
    backBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            finish();
        }
    });

}

}

CustomWishlistsAdapter.java

public class CustomWishlistsAdapter extends SimpleCursorAdapter {

private int layout;
private ImageButton editBtn;
private ImageButton delBtn;
LayoutInflater inflator;

public CustomWishlistsAdapter(Context context, int layout, Cursor c,String[] from, int[] to) {
    super(context, layout, c, from, to,0);
    this.layout = layout;
    inflator= LayoutInflater.from(context);
}

public View newView(Context context, Cursor cursor, ViewGroup parent) {     
    View v = inflator.inflate(layout, parent, false);
    return v;
}

@Override
public void bindView(View v, final Context context, Cursor c) {
    final int id = c.getInt(c.getColumnIndex(Wishlists.ID));
    final String name = c.getString(c.getColumnIndex(Wishlists.NAME));
    final String note = c.getString(c.getColumnIndex(Wishlists.NOTE));
    final byte[] image = c.getBlob(c.getColumnIndex(Wishlists.IMAGE));
    ImageView iv = (ImageView) v.findViewById(R.id.inputphoto);

    if (image != null) {
        if (image.length > 3) {
            iv.setImageBitmap(BitmapFactory.decodeByteArray(image, 0,image.length));
        }
    }

    TextView tname = (TextView) v.findViewById(R.id.name);
    tname.setText(name);

    final SQLiteConnector sqlCon = new SQLiteConnector(context);

    editBtn=(ImageButton) v.findViewById(R.id.edit_btn);    
    editBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent=new Intent(context,AddEditWishlists.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);               
            intent.putExtra("id", id);
            intent.putExtra("name", name);
            intent.putExtra("note", note);
            intent.putExtra("blob", image);
            context.startActivity(intent);
        }

    });

    delBtn=(ImageButton) v.findViewById(R.id.del_btn);  
    delBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            sqlCon.deleteWishlist(id);  
            Intent intent=new Intent(context,MyWishlistsActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }

    });     

    v.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent=new Intent(context,ViewWishlist.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);               
            intent.putExtra("id", id);
            intent.putExtra("name", name);
            intent.putExtra("note", note);
            intent.putExtra("blob", image);
            context.startActivity(intent);
        }
    });

}

}

This is my code. Please help me how to add http post request on this code.. And also the php on the Server side .

  • 写回答

1条回答 默认 最新

  • duanjie9630 2013-07-19 08:56
    关注

    For the Android HttpPost (to send JSON serialized data to a server)

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("url_of_the_server");
    JSONObject json = new JSONObject();
    json.put("name", name);
    json.put("note", note);
    StringEntity se = new StringEntity(json.toString());
    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    post.setEntity(se);
    HttpResponse response = client.execute(post);
    //With response you can check the server return status code(to check if the request has been made correctly like so
    StatusLine sLine = response.getStatusLine();
    int statusCode = sLine.getStatusCode();
    

    For more information on how to call a php web service there is a pretty nice tutorial that can be found here

    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?