i want to send my data in form of json to server using post method in android.
here is my format |data1|data2|data3|<>|data11|data22|data33
hope some example since i difficult to catch the procedure of post method.
Anyidea?
Edit:
my json format |data1|data2|data3|<>|data11|data22|data33|
where each data is a plain text (text get from database)
how can create it??
This blog post seems to talk about just that.
Post JSON Using Android And HttpClient
Edit: I saw your reply. Here's how. Hope this does the trick :)
public static void main(String[] args) {
File file = new File("<path to json file>");
FileInputStream fis;
String json = "";
try {
fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
// dis.available() returns 0 if the file does not have more lines.
while (dis.available() != 0) {
json += dis.readLine();
}
// dispose all the resources after using them.
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Essentially after this you would create the string entity to send
StringEntity st = new StringEntity(json.toString());
Then just follow the steps in that link
Haha, edit for your 2nd question: Just create a string with the text from the database. Thats all there is to it. Then create a StringEntity like the one above.
Related
I was testing a method by which I could upload an Image available on my Android device into a BLOB field of a mySQL table. Couple of posts I ran into spoke about broader points but I was not able to tie them all up together.
Here is a part of my code. This is written in a new Thread of a service.
try {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addTextBody(StaticVariables.filename, fileNames[i]);
//builder.addBinaryBody(StaticVariables.image, new File (getExternalCacheDir().getParent() + File.separator + StaticVariables.bills + File.separator + fileNames[i]));
builder.addTextBody(StaticVariables.image, getStringImage(Uri.fromFile(new File(getExternalCacheDir().getParent() + File.separator + StaticVariables.bills + File.separator + fileNames[i]))));
httppost.setEntity(builder.build());
HttpResponse response = httpClient.execute(httppost);
entity = response.getEntity();
String line = StaticVariables.emptyString;
InputStream instream = entity.getContent();
BufferedReader obr = new BufferedReader(new InputStreamReader(instream));
while ((line = obr.readLine()) != null) {
confirmed.add(line);
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
THE main issue I am facing now is that on execution, an exception is being raised where it states "413: Request Entity is too large". This occurs if I pass the file in the Binary format (the commented line of code) or the Text format.
The solution to write the images on to a folder of the server has already been done by me but I am curious to know if there is some way I could get them directly on to the DB.
Other information I should share is that I am running a very basic godaddy server and hence might not have any access to change any parameters on the server.
Let me know if you would require any other information.
Appreciate any input.
I have an application and I need to get some data from my database(MySQL and it stays on web, not local). I think a simple RestFul webservice will be the best option for me to access this database and get the data. However, I m not able to create the webservice. I did some researches but I got confused. All I need is just accessing the database and get a few data from the table. Please give me some help to create the neccessary webservice. I don't want it to be a complex webservice. Thank to you all
this is php page of web-service. in this userid is taken from android java file that requesting that data. and after that selecting data from mySql it will simply echo all data and that will be given to java file as response.
seluser_profile.php
<?php
//$con=mysql_connect("localhost","root","");
//mysql_select_db("android_db",$con);
$con=mysql_connect("localhost","root","");
mysql_select_db("android_db",$con);
$uname=$_POST['userid'];
$q="select * from user_details where username='$uname'";
$rec=mysql_query($q);
if(mysql_num_rows($rec)==1)
{
$arr=mysql_fetch_array($rec);
echo $arr[0]+" "+$arr[2]+" "+$arr[3];
}
else
{
echo "false";
}
?>
Java code for requesting to web service.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.0.2/webservice/seluser_profile.php");
try {
// Add your data
//Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_LONG).show();
List<NameValuePair> namevpair = new ArrayList<NameValuePair>(2);
namevpair.add(new BasicNameValuePair("userid",valueIWantToSend));//in this first argument is name of post variable which we will use in php web service as name of post varible $_POST['fname'];
httppost.setEntity(new UrlEncodedFormEntity(namevpair));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
str = inputStreamToString(response.getEntity().getContent()).toString();
//Toast.makeText(getApplicationContext(), "your answer="+str, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
use this java code in doInBackground method of Asynctask class. otherwise it will give you network handler exception.
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
and also add this function for string building from inputstream.
Here is a link, You may seen this while surfing, I know this is not an answer , but I cannot comment bcz I dnt have enough Rep.
http://www.androidhive.info/2014/01/how-to-create-rest-api-for-android-app-using-php-slim-and-mysql-day-12-2/
I used this in one of my project, customization was very easy..and a great tutorial.
I read a json file which contains some telephone numbers. Something like this:
"number" : "416‐736‐5088"
I parse it using JsonReader it and save it into a list.
private void populateOfficeList() throws IOException {
officeList.clear();
InputStream in = null;
JsonReader jsonReader = null;
try {
in = openFileInput(OFFICE_JSON);
System.out.println("got in " + in);
jsonReader = new JsonReader(new InputStreamReader(in, "UTF-8"));
readofficeListMessageArray(jsonReader, officeList);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
jsonReader.close();
in.close();
}
}
Everything works fine. Its parsed and saved properly. However when i fetch these numbers for display,they get displayed like this:
416�736�5217
I am already using UTF-8 for conversion. How do I get rid of these characters �
Welcome to the wonderful world of character encoding. Make sure the file you're reading is saved in UTF-8 also.
i am thinking about there are some many way to store data in file , i found one of this is useing buffedinputstream ,but i really don't know is it good ??
if i using like this , it will be most fast ??
is there any other suggestion ?? i just want make the file io more fast !!
public ArrayList<String> testReadingTxtFromFile(){
ArrayList<String> result = null;
try {
FileInputStream fIn = openFileInput("cacheingtext.txt");
InputStreamReader isr = new InputStreamReader(fIn);
BufferedReader reader = new BufferedReader(isr);
String line;
while((line = reader.readLine() )!= null){
String[] datas = line.split(",");
Log.i("check", datas.length+"");
for(String data:datas){
Log.i("check", data);
result.add(data);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public void testWritingTxtToFile(String[] messages){
try {
FileOutputStream fo = openFileOutput("cacheingtext.txt", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fo);
BufferedWriter writer = new BufferedWriter(osw);
int size = messages.length;
for(int i=0;i<size;i++){
writer.write(messages[i]);
writer.write(",");
Log.i("check", "write "+messages[i]);
}
writer.flush();
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The Reader/Writer class hierarchy is character-oriented, and the Input Stream/Output Stream class hierarchy is byte-oriented.
Basically there are two types of streams.Byte streams that are used to handle stream of bytes and character streams for handling streams of characters.
What I see in your case is that you are using a byte-oriented Stream.
Character streams are often "wrappers" for byte streams. The character stream uses the byte stream to perform the physical I/O, while the character stream handles translation between characters and bytes. FileReader, for example, uses FileInputStream, while FileWriter uses FileOutputStream.
So,if you want to generally deal with Characters (reading text files), go for Character-oriented Stream(Reader/Writer). But if you want to process the content independent of what type of file is it, go for byte-oriented stream.
I am creating an Android application that connects to the Fogbugz XML API (sends a request to the API, receives back an XML file). Right now, I am creating a service that will handle these requests, and parse each in order to access usable information. What would be the best way to do this? If I am getting an inputStream, should I use the SAX parser?
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("My URL THAT RETURNS AN XML FILE");
HttpResponse response;
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
String responseString = "";
String temp;
while ((temp=bufferedReader.readLine()) != null)
{
responseString += temp;
}
if (entity != null) {
entity.consumeContent();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I suggest that you use some XML DOM library like XOM or Dom4j. It will be much easier for you to work with tree structure than with SAX events. Personally, I use XOM in Foglyn -- FogBugz for Eclipse plugin. You can pass InputStream directly to your SAX/XOM/Dom4j parser, there is no need to build string first. Furthermore, make sure you use correct encoding ... your code is broken in this regard. (When you pass InputStream to your parser, this is handled by parser. In XOM you can use new Builder().build(InputStream) method).
One FogBugz API hint ... when getting details about case, and you don't need events (comments), don't fetch them at all. I.e. don't put events into list of columns.