Send JSON object via HttpPost method

by Alok Kulkarni » Tue, 08 Sep 2009 21:19:18 GMT


Sponsored Links
 Any answers ??





--~--~---------~--~----~------------~-------~--~----~



Send JSON object via HttpPost method

by Wayne Wenthin » Wed, 09 Sep 2009 05:39:03 GMT


 A snippet for what I do...
public HttpResponse updateGirl(String url, Pawn girl, int pawnID) {
HttpClient httpclient = new DefaultHttpClient();
HttpPut httpput = new HttpPut(url);

// Execute the request

try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
39);
nameValuePairs.add(new BasicNameValuePair("id", Integer
.toString(pawnID)));
......  Many nameValuePairs later.....


httpput.addHeader("Content-Type",
"application/x-www-form-urlencoded");
httpput.setEntity(new UrlEncodedFormEntity(nameValuePairs,
HTTP.UTF_8));
 HttpResponse response = httpclient.execute(httpput);
return response;

} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;

}

Hope that helps.   I struggled with it for a couple of weeks before I found
a site that had a good source.









-- 
Writing code is one of few things
that teaches me I don't know everything.

--~--~---------~--~----~------------~-------~--~----~


Sponsored Links


Send JSON object via HttpPost method

by Alok Kulkarni » Wed, 09 Sep 2009 16:44:42 GMT


 ey Wayne, thanks a lot..
I have also got a solution parallely which i would like to post

URL url = new URL(serverURL);

// open the conncetion
HttpURLConnection connection =
(HttpURLConnection)url.openConnection();

// Let the run-time system (RTS) know that we want input.
connection.setDoInput(true);
// Let the RTS know that we want to do output
connection.setDoOutput(true);
// No caching, we want the real thing
connection.setUseCaches(false);
// set the content type property
connection.setRequestProperty("Content-type",strContenttype);

// set request method
connection.setRequestMethod("POST");
// create the post body to send
String content = credDevPair.toString();
Log.i("Request ====....... ",content);
DataOutputStream printout = new DataOutputStream (
connection.getOutputStream () );

// send the data
printout.writeBytes(content);
printout.flush();
printout.close();
String output =
convertStreamToString(connection.getInputStream());
Log.i("Response 1....... ",output);
// A Simple JSONObject Creation
JSONObject json=new JSONObject(output);

Log.i("Praeda","<jsonobject>\n"+json.toString()+"\n</jsonobject>");

// A Simple JSONObject Parsing
JSONArray nameArray=json.names();
JSONArray valArray=json.toJSONArray(nameArray);
for(int i=0; i<valArray.length() ;i++)
{

Log.i("Praeda","<jsonname"+i+">\n"+nameArray.getString(i)+"\n</jsonname"+i+">\n"

+"<jsonvalue"+i+">\n"+valArray.getString(i)+"\n</jsonvalue"+i+">");
}
//BufferedReader input = new BufferedReader ( new
InputStreamReader(connection.getInputStream()) );

}catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();

}catch(Exception ex)
{

}

}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the
BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which
means
* there's no more data to read. Each line will appended to a
StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new
InputStreamReader(is));
StringBuilder sb = new StringBuilder();

String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}

return sb.toString();
}


On Wed, Sep 9, 2009 at 3:08 AM, Wayn



Send JSON object via HttpPost method

by Wayne Wenthin » Thu, 10 Sep 2009 08:58:06 GMT


 ep that is what I vaguely based mine on.   I recognize the Praeda line.   I
had to modify mine because I was not sending back an array of json objects
but a specific one that I handle based on the ID on the backend with ruby.

On Wed, Sep 9, 2009 at 1:43 AM, Alok Kulkarni <kulsu...@gmail.com> wrote:



--
Writing code is one of few things
that teaches me I don't know everything.

--~--~---------~--~----~------------~-------~--~----~



Send JSON object via HttpPost method

by Alok Kulkarni » Thu, 10 Sep 2009 13:28:31 GMT


 k.. ya i had taken that code part from the forum itself. :)

On Thu, Sep 10, 2009 at 6:27 AM, Wayne Wenthin <wa...@fuligin.com> wrote:


--~--~---------~--~----~------------~-------~--~----~



Other Threads

1. Why there is no drawable-ldpi directory under frameworks/base/core/res/res

Hi,

In android source code, frameworks/base/core/res/res are where android
resource files are being saved.
My question is why there is no drawable-lpi, there are only
drawable-hpi , drawable-mpi.
Isn't drawable-lpi is for low density resources, whereas drawable-hpi
for high density and drawable-mpi for middle density?

Thank you.

-- 

2. The Force Close Error is suddenly back...

Hi,

I am trying to load videos from my emulated sdcard into my implemented
GridView, it worked fine before, when I used the GridView example from
Google...but now I get a Force close error when I try to open the app.

The entire app works (or rather should work) like this a TabView is
launched that includes 2 tabs (GalleryView.java and main.xml), each
tab loads a GridView (EditGalleryView.java and ShareGalleryView.java).
Before I tried loading videos into the gridView I simply used the
GridView example as starting point. Now on basis of this example I am
trying to load videos into my GridView from the sdcard, which
apparently seems to cause a Force Close Error.

If someone could help me find the problem that's causing this, it
would be great because I really don't know what's wrong now ...
Thanks in Advance

Here is the code I use:

The Manifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.mobilevideoeditor.moved"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/
app_name">
               <activity android:name=".EditGalleryView"
                            android:label="@string/app_name"
                            android:theme="@android:style/
Theme.NoTitleBar">
                <intent-filter>
                    <action android:name="android.intent.action.PICK"/
                </intent-filter>
             </activity>
           <activity android:name=".ShareGalleryView"
                            android:label="@string/app_name"
                            android:theme="@android:style/
Theme.NoTitleBar">
                    <intent-filter >
                        <action
android:name="android.intent.action.SEND"/>
                    </intent-filter>
                </activity>
           <activity android:name=".GalleryView"
                        android:label="@string/app_name"
                        android:theme="@android:style/
Theme.NoTitleBar">
                <intent-filter>
                        <action
android:name="android.intent.action.MAIN" />
                    <category
android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
           </activity>
    </application>
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE"/>
</manifest>

The GalleryView.java:

package com.mobilevideoeditor.moved;

import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.widget.TabHost;

public class GalleryView extends TabActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Resources res = getResources(); // Resource object to get
Drawables
    TabHost tabHost = getTabHost();  // The activity TabHost
    TabHost.TabSpec spec;  // Reusable TabSpec for each tab
    Intent intent;  // Reusable Intent for each tab

    // Create an Intent to launch an EditGallery for the tab (to be
reused)
    intent = new Intent().setClass(this, EditGalleryView.class);

    // Initialize a TabSpec for each tab and add it to the TabHost
    spec = tabHost.newTabSpec("edit").setIndicator("Edit",
                      res.getDrawable(R.layout.ic_tab_edit))
                  .setContent(intent);
    tabHost.addTab(spec);

    intent = new Intent().setClass(this, ShareGalleryView.class);
    spec = tabHost.newTabSpec("share").setIndicator("Share",
                      res.getDrawable(R.layout.ic_tab_share))
                      .setContent(intent);
tabHost.addTab(spec);

    tabHost.setCurrentTab(0);
}
}

The EditGalleryView.java (which seems to cause my problem):

package com.mobilevideoeditor.moved;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.VideoView;




public class EditGalleryView extends Activity {
    Uri[] vidUris;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.videogrid);

        GridView vGrid=(GridView) findViewById(R.id.vgrid);
        vGrid.setAdapter(new VideoAdapter(this));

        Uri uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;

        Log.d("EditGalleryView", "uri:"+uri);
 String[] projection = {
                MediaStore.Video.Media.DESCRIPTION,
                MediaStore.Video.Media.DATA
    };

        Cursor c = this.managedQuery(uri, projection, null, null,
                MediaStore.Video.Media.DATE_ADDED);
                         Log.d("EditGalleryView", "vids available:"
+c.getCount());

                         ArrayList<Uri> experimentVids = new
ArrayList<Uri>();


                             if (c.getCount() != 0) {
                                 c.moveToFirst();
                                 //
experimentVids.add(Uri.parse(c.getString(1)));
                                 while (c.moveToNext()) {
 
experimentVids.add(Uri.parse(c.getString(1)));

                                  }
                      }
                             Log.d("ClassName",
"experimentVids.length:" +experimentVids.size());
                                                  if
(experimentVids.size() != 0) {
                                                    vidUris = new
Uri[experimentVids.size()];
                                                      for (int i = 0;
i < experimentVids.size(); i++) {
                                                          vidUris[i] =
experimentVids.get(i);
                                                      }
 
Log.d("EditGalleryView", "vidUris:"+vidUris.length);
                                                  }
                                              }


    public class VideoAdapter extends BaseAdapter {
        private Context mContext;

        public VideoAdapter(Context c) {
            mContext = c;
        }

        public int getCount() {
            //return mThumbIds.length;
            return vidUris.length;
        }

        public Object getItem(int position) {
            //return null;
            return position;
        }

        public long getItemId(int position) {
            //return 0;
            return position;
        }

        // create a new ImageView for each item referenced by the
Adapter
        public View getView(int position, View convertView, ViewGroup
parent) {
           VideoView videoView;
            if (convertView == null) {  // if it's not recycled,
initialize some attributes
                videoView = new VideoView(mContext);
                videoView.setVideoURI(vidUris[position]);
                videoView.setLayoutParams(new
GridView.LayoutParams(85, 85));
               //
videoView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                videoView.setPadding(8, 8, 8, 8);
            } else {
                videoView = (VideoView) convertView;
            }

          //  imageView.setImageResource(mThumbIds[position]);
            return videoView;
        }

And this is my LogCat Error Output:

07-16 19:40:45.074: ERROR/AndroidRuntime(225): Uncaught handler:
thread main exiting due to uncaught exception
07-16 19:40:45.124: ERROR/AndroidRuntime(225):
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.mobilevideoeditor.moved/
com.mobilevideoeditor.moved.GalleryView}: java.lang.RuntimeException:
Unable to start activity ComponentInfo{com.mobilevideoeditor.moved/
com.mobilevideoeditor.moved.EditGalleryView}:
java.lang.NullPointerException
07-16 19:40:45.124: ERROR/AndroidRuntime(225):     at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:
2496)
07-16 19:40:45.124: ERROR/AndroidRuntime(225):     at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:
2512)
07-16 19:40:45.124: ERROR/AndroidRuntime(225):     at
android.app.ActivityThread.access$2200(ActivityThread.java:119)
07-16 19:40:45.124: ERROR/AndroidRuntime(225):     at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
07-16 19:40:45.124: ERROR/AndroidRuntime(225):     at
android.os.Handler.dispatchMessage(Handler.java:99)
07-16 19:40:45.124: ERROR/AndroidRuntime(225):     at
android.os.Looper.loop(Looper.java:123)
07-16 19:40:45.124: ERROR/AndroidRuntime(225):     at
android.app.ActivityThread.main(ActivityThread.java:4363)
07-16 19:40:45.124: ERROR/AndroidRuntime(225):     at
java.lang.reflect.Method.invokeNative(Native Method)
07-16 19:40:45.124: ERROR/AndroidRuntime(225):     at
java.lang.reflect.Method.invoke(Method.java:521)
07-16 19:40:45.124: ERROR/AndroidRuntime(225):     at
com.android.internal.os.ZygoteInit
$MethodAndArgsCaller.run(ZygoteInit.java:860)
07-16 19:40:45.124: ERROR/AndroidRuntime(225):     at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
07-16 19:40:45.124: ERROR/AndroidRuntime(225):     at
dalvik.system.NativeStart.main(Native Method)
07-16 19:40:45.124: ERROR/AndroidRuntime(225): Caused by:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.mobilevideoeditor.moved/
com.mobilevideoeditor.moved.EditGalleryView}:
java.lang.NullPointerException
07-16 19:40:45.124: ERROR/AndroidRuntime(225):     at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:
2496)
07-16 19:40:45.124: ERROR/AndroidRuntime(225):     at
android.app.ActivityThread.startActivityNow(ActivityThread.java:2335)
07-16 19:40:45.124: ERROR/AndroidRuntime(225):     at
android.app.LocalActivityManager.moveToState(LocalActivityManager.java:
127)
07-16 19:40:45.124: ERROR/AndroidRuntime(225):     at
android.app.LocalActivityManager.startActivity(LocalActivityManager.java:
339)
07-16 19:40:45.124: ERROR/AndroidRuntime(225):     at
android.widget.TabHost
$IntentContentStrategy.getContentView(TabHost.java:648)
07-16 19:40:45.124: ERROR/AndroidRuntime(225):     at
android.widget.TabHost.setCurrentTab(TabHost.java:320)
07-16 19:40:45.124: ERROR/AndroidRuntime(225):     at
android.widget.TabHost.addTab(TabHost.java:213)
07-16 19:40:45.124: ERROR/AndroidRuntime(225):     at
com.mobilevideoeditor.moved.GalleryView.onCreate(GalleryView.java:28)
07-16 19:40:45.124: ERROR/AndroidRuntime(225):     at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:
1047)
07-16 19:40:45.124: ERROR/AndroidRuntime(225):     at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:
2459)
07-16 19:40:45.124: ERROR/AndroidRuntime(225):     ... 11 more
07-16 19:40:45.124: ERROR/AndroidRuntime(225): Caused by:
java.lang.NullPointerException
07-16 19:40:45.124: ERROR/AndroidRuntime(225):     at
com.mobilevideoeditor.moved.EditGalleryView
$VideoAdapter.getCount(EditGalleryView.java:73)
07-16 19:40:45.124: ERROR/AndroidRuntime(225):     at
android.widget.GridView.setAdapter(GridView.java:128)
07-16 19:40:45.124: ERROR/AndroidRuntime(225):     at
com.mobilevideoeditor.moved.EditGalleryView.onCreate(EditGalleryView.java:
28)
07-16 19:40:45.124: ERROR/AndroidRuntime(225):     at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:
1047)
07-16 19:40:45.124: ERROR/AndroidRuntime(225):     at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:
2459)
07-16 19:40:45.124: ERROR/AndroidRuntime(225):     ... 20 more

-- 

3. chat software , android based

4. android 1.5 tilt control tutorial

5. Detecting version of Android at runtime

6. Hide an app from the user

7. Do other devs get asked to list their apps on foreign market sites?