Posting a Single image to server locally - android

I am trying for a simple image upload to local server
What I am trying to do :: I am trying to upload one image to server on click of button
I have referred this link
But i don't know how to implement the postData() function
Link i am trying to post the image::
http://10.0.2.2/Details/
with a name key for the image
MainActivity.java
public class MainActivity extends Activity {
Button submit;
ProgressDialog pDialog;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
submit = (Button) findViewById(R.id.SUBMIT_BUTTON_ID);
imageView = (ImageView) findViewById(R.id.imageView1);
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new MainTest().execute();
}
});
}
public void postData() {
}
/**
* Method to post the image to the server.
* U will have to change the url which will accept the image data.
*/
public class MainTest extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
postData();
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// data=jobj.toString();
pDialog.dismiss();
}
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="32dp"
android:clickable="false"
android:src="#drawable/image" />
<Button
android:id="#+id/SUBMIT_BUTTON_ID"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="47dp"
android:text="SUBMIT" />
</LinearLayout>
Any help on resolving this !
[EDIT- What i tried before]- I was not successful in getting the result
public class MainActivity extends Activity {
Button submit;
ProgressDialog pDialog;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
submit = (Button) findViewById(R.id.SUBMIT_BUTTON_ID);
imageView = (ImageView) findViewById(R.id.imageView1);
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new MainTest().execute();
}
});
}
/**
* Method to post the image to the server.
* U will have to change the url which will accept the image data.
* #throws IOException
*/
public void postImageData() throws IOException
{
Drawable myDrawable = getResources().getDrawable(R.drawable.image);
Bitmap bitmap = ((BitmapDrawable)myDrawable).getBitmap();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://10.0.2.2:7002/Details/");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
try{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();
ByteArrayBody bab = new ByteArrayBody(data, "forest.jpg");
reqEntity.addPart("key", bab);
}
catch(Exception e){
Log.v("MY-Error-Tag", "I got an error"+e);
reqEntity.addPart("key", new StringBody(""));
}
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
}
public class MainTest extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
try {
postImageData();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// data=jobj.toString();
pDialog.dismiss();
}
}
}
[FINAL-EDIT]
package com.example.datapostingproject;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
public class MainActivity extends Activity {
Button submit;
ProgressDialog pDialog;
InputStream is;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
submit = (Button) findViewById(R.id.SUBMIT_BUTTON_ID);
imageView = (ImageView) findViewById(R.id.imageView1);
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new MainTest().execute();
}
});
}
/**
* Method to post the image to the server.
* U will have to change the url which will accept the image data.
* #throws IOException
*/
public void postImageData() {
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String ba1=Base64.encodeToString(ba,Base64.DEFAULT);
ArrayList<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("key",ba1));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://10.0.2.2:7002/Details/");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
}
public class MainTest extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
postImageData();
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// data=jobj.toString();
pDialog.dismiss();
}
}
}
{stack stace on debugging } - in log
12-08 14:47:50.628: I/.......(433): TypeError: Cannot read property 'key' of undefined
12-08 14:47:50.628: I/.......(433): at C:\ExpressPractice\imageUpload\app.js:17:32
12-08 14:47:50.628: I/.......(433): at callbacks (C:\ExpressPractice\imageUpload\node_modules\express\lib\router\index.js:164:37)
12-08 14:47:50.628: I/.......(433): at param (C:\ExpressPractice\imageUpload\node_modules\express\lib\router\index.js:138:11)
12-08 14:47:50.628: I/.......(433): at pass (C:\ExpressPractice\imageUpload\node_modules\express\lib\router\index.js:145:5)
12-08 14:47:50.628: I/.......(433): at Router._dispatch (C:\ExpressPractice\imageUpload\node_modules\express\lib\router\index.js:173:5)
12-08 14:47:50.628: I/.......(433): at Object.router (C:\ExpressPractice\imageUpload\node_modules\express\lib\router\index.js:33:10)
12-08 14:47:50.628: I/.......(433): at next (C:\ExpressPractice\imageUpload\node_modules\express\node_modules\connect\lib\proto.js:193:15)
12-08 14:47:50.628: I/.......(433): at multipart (C:\ExpressPractice\imageUpload\node_modules\express\node_modules\connect\lib\middleware\multipart.js:86:27)
12-08 14:47:50.628: I/.......(433): at C:\ExpressPractice\imageUpload\node_modules\express\node_modules\connect\lib\middleware\bodyParser.js:57:9
12-08 14:47:50.628: I/.......(433): at C:\ExpressPractice\imageUpload\node_modules\express\node_modules\connect\lib\middleware\urlencoded.js:76:7
12-08 14:47:50.639: E/log_tag(433): Error in http connection java.lang.IllegalStateException: Content has been consumed
second-error trace after removing is = entity.getContent();
12-08 15:04:10.971: I/.......(461): TypeError: Cannot read property 'key' of undefined
12-08 15:04:10.971: I/.......(461): at C:\ExpressPractice\imageUpload\app.js:17:32
12-08 15:04:10.971: I/.......(461): at callbacks (C:\ExpressPractice\imageUpload\node_modules\express\lib\router\index.js:164:37)
12-08 15:04:10.971: I/.......(461): at param (C:\ExpressPractice\imageUpload\node_modules\express\lib\router\index.js:138:11)
12-08 15:04:10.971: I/.......(461): at pass (C:\ExpressPractice\imageUpload\node_modules\express\lib\router\index.js:145:5)
12-08 15:04:10.971: I/.......(461): at Router._dispatch (C:\ExpressPractice\imageUpload\node_modules\express\lib\router\index.js:173:5)
12-08 15:04:10.971: I/.......(461): at Object.router (C:\ExpressPractice\imageUpload\node_modules\express\lib\router\index.js:33:10)
12-08 15:04:10.971: I/.......(461): at next (C:\ExpressPractice\imageUpload\node_modules\express\node_modules\connect\lib\proto.js:193:15)
12-08 15:04:10.971: I/.......(461): at multipart (C:\ExpressPractice\imageUpload\node_modules\express\node_modules\connect\lib\middleware\multipart.js:86:27)
12-08 15:04:10.971: I/.......(461): at C:\ExpressPractice\imageUpload\node_modules\express\node_modules\connect\lib\middleware\bodyParser.js:57:9
12-08 15:04:10.971: I/.......(461): at C:\ExpressPractice\imageUpload\node_modules\express\node_modules\connect\lib\middleware\urlencoded.js:76:7
But from POSTMAN when i send image it works for 'key'
Still not successful in getting image posted !

Use the below an try
public void postData() {
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String ba1=Base64.encodeToString(ba,Base64.DEFAULT);
ArrayList<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",ba1));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://10.0.2.2:7002/Details/");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
}
Edit:
Just for testing try uploading image from sdcard using file path
try
{
String filepath= Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"Download"+File.separator+"ic_launcher.png";
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("your url");
File file = new File(filepath);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String _response=EntityUtils.toString(entity);
Log.i(".......",_response);
}catch(Exception e){
e.printStacktrace();
}

Finally with the help of Raghunandan ...... from one of the answers .... found the solution
Ill post the complete answer so that .... this might be helpful to some-one
MainActivity.java
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
public class MainActivity extends Activity {
Button submit;
ProgressDialog pDialog;
InputStream is;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
submit = (Button) findViewById(R.id.SUBMIT_BUTTON_ID);
imageView = (ImageView) findViewById(R.id.imageView1);
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new MainTest().execute();
}
});
}
/**
* Method to post the image to the server.
* U will have to change the url which will accept the image data.
* #throws IOException
*/
public void postImageData() {
try
{
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://10.0.2.2:7002/Details/");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
try{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmapOrg.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();
ByteArrayBody bab = new ByteArrayBody(data, "forest.jpg");
reqEntity.addPart("key", bab);
}
catch(Exception e){
//Log.v("Exception in Image", ""+e);
reqEntity.addPart("picture", new StringBody(""));
}
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
}catch(Exception e){
e.getStackTrace();
}
}
public class MainTest extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
postImageData();
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// data=jobj.toString();
pDialog.dismiss();
}
}
}
ExpressJS code
app.js
var express=require('express');
var fs=require('fs');
var http=require('http');
var crypto=require('crypto');
var app=express();
app.set('port',process.env.PORT||7002);
app.use('/Details',express.static(__dirname+'/public/images'));
//.use(express.cookieParser());
app.use(express.bodyParser());
app.post('/Details/',function(req,res,next){
var file_name=req.files.key.originalFilename;
console.log(file_name);
crypto.randomBytes(8, function(ex, buf) {
var array = req.files.key.originalFilename.split('.');
var type = array[array.length - 1];
var name = buf.toString('hex') + '.' + type;
fs.rename(req.files.key.path, './public/images/' + name, function(e) {
if (e) {
res.send(500, e.message);
} else
{
res.send("I got the message - This i confirm");
}
});
});
});
app.get('/Details/',function(req,res){
res.send("Image displayed");
});
http.createServer(app).listen(app.get('port'),function(){
console.log('Express server listening on port'+app.get('port'));
});
Point to keep in mind ::
Make sure you send data as multipart from client(android)
Then make sure u accept data on server side also as multipart

Related

how to call method in login page

i'm currently trying to make a validation for a login page, which is to validate whether the account is in my database or not, i'm to call the method of invokelogin(), but it seems but i don't know how to call the method, need some help with it.
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
public class Activity_Login extends Activity{
private Button btnSignIn;
String username;
String pass;
public static final String USER_NAME = "USERNAME";
EditText txtUser;
EditText Pass;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btnSignIn = (Button) findViewById(R.id.btnSignIn);
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
launchActivity3();
}
});
}
public void launchActivity3() {
txtUser = (EditText) findViewById(R.id.txtUser);
Pass = (EditText) findViewById(R.id.txtPass);
if (txtUser.getText().toString().equals("")) {
Toast.makeText(Activity_Login.this, "UserName must Be Filled", Toast.LENGTH_SHORT).show();
} else if (Pass.getText().toString().equals("")) {
Toast.makeText(Activity_Login.this, "Password must be Filled", Toast.LENGTH_SHORT).show();
} else {
invokeLogin();
}
Intent intent_SignIn = new Intent(Activity_Login.this, Activity_Drawer2.class);
startActivity(intent_SignIn);
}
public void invokeLogin(View view){
username = txtUser.getText().toString();
pass = Pass.getText().toString();
login(username,pass);
}
private void login (final String username, String pass){
class LoginAsync extends AsyncTask<String, Void, String> {
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(Activity_Login.this, "Please wait", "Loading...");
}
#Override
protected String doInBackground(String... params) {
String uname = params[0];
String pass = params[1];
InputStream is = null;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", uname));
nameValuePairs.add(new BasicNameValuePair("password", pass));
String result = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.10.1.11/login.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result) {
String s = result.trim();
loadingDialog.dismiss();
if (s.equalsIgnoreCase("success")) {
Intent intent = new Intent(Activity_Login.this, Activity_Drawer2.class);
intent.putExtra(USER_NAME, username);
finish();
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Invalid User Name or Password", Toast.LENGTH_LONG).show();
}
}
}
LoginAsync la = new LoginAsync();
la.execute(username, pass);
}
}
You can pass txtUser and Pass to invokeLogin();
so it look like invokeLogin(txtUser,Pass);
Then your invokeLogin method
public void invokeLogin(String username, String pass){
login(username,pass);
}

populating spinner with data from database

what i am trying to do is to first insert some values in the database(see insertvalues function) and then retrieving all the data from database into the spinner(see getvalues function).i successfully retrieve data from database which i checked through the textboxes.but when i set this data to my spinner adapter and run the app,i get an empty spinner.i understand that i should first write the line
My_spinner=(spinner)findViewbyid(--) and then call the getvalues function,but when i try to move this line(My_spinner=(spinner)findViewbyid(--) somewhere else,my app does not work anymore and says unfortunately the app was closed.i took quite alot of time to figure out the problem but i could not,please help.
package com.example.gcmclientapp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class GcmServer extends Activity {
void showToast(CharSequence msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
// declarations for creating the database
SQLiteDatabase mydb;
String name_from_spinner; // this will be used to filter the database for the required registrationID
private static String DBNAME = "new1.db"; // this is our database..change it when you use
private static String TABLE = "MY_TABLE";
//end of dec
EditText et;
String regId,userName;
Button b;
TextView tv,tv2;
String temp="";
String[] arr;
Spinner My_spinner;
InputStream is=null;
ArrayList<String> my_array1 = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gcmserver);
b= (Button)findViewById(R.id.button1);
et=(EditText)findViewById(R.id.editText1);
tv=(TextView)findViewById(R.id.textView1);
tv2=(TextView)findViewById(R.id.textView2);
regId = getIntent().getStringExtra("REGID");
userName = getIntent().getStringExtra("USER");
insertvalues();
getTableValues();
My_spinner = (Spinner) findViewById(R.id.spinner1);
//setting on click listeners for the items of the spinner
My_spinner.setOnItemSelectedListener(
new OnItemSelectedListener() {
public void onItemSelected(
AdapterView<?> parent, View view, int position, long id) {
name_from_spinner=my_array1.get(position);
showToast(name_from_spinner);// get the name that has been clicked in the spinner
}
public void onNothingSelected(AdapterView<?> parent) {
showToast("Please enter contact");
}
});
// when the send button is clicked,we will extract the message from editText,regID and send to sendtoserver
// send button
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String ID = null;
String REGID=null;
String NAME=null;
String message =et.getText().toString(); //extract message from edit text
// extract registration number
try {
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
Cursor allrows = mydb.rawQuery("SELECT * FROM " + TABLE, null);
if (allrows.moveToFirst()) {
do {
ID = allrows.getString(0);
REGID = allrows.getString(1);
NAME = allrows.getString(2);
if(NAME.equals(name_from_spinner)) // string comparison
{
break;
}
} while (allrows.moveToNext());
showToast("left loop");
}
allrows.close();
mydb.close();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Error encountered.",
Toast.LENGTH_LONG);
}
//tv.setText(REGID);
System.out.print(REGID);
sendToServer(message,REGID);
}
});
}
//#########################################INSERT############################################################
public void insertvalues()
{
StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("regid", regId));
nameValuePairs.add(new BasicNameValuePair("name", userName));
try {
//tv2.setText(regId);
HttpClient httpClient=new DefaultHttpClient();
HttpPost httpPost=new HttpPost("http://192.168.1.3/new.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response=httpClient.execute(httpPost);
HttpEntity entity=response.getEntity();
is=entity.getContent();
showToast("data inserted successfully");
}
catch(ClientProtocolException e)
{
Log.e("clientProtocol","Log_tag");
e.printStackTrace();
}catch(IOException e)
{
Log.e("log_tag","ioexception");
e.printStackTrace();
}
}
public void sendToServer(final String message,final String ID){
//tv2.setText(ID);
new AsyncTask<String, Void, String>(){
// changes are needed here
#Override
protected String doInBackground(String... params) {
try {
HttpResponse response = null;
HttpParams httpParameters = new BasicHttpParams();
HttpClient client = new DefaultHttpClient(httpParameters);
String url="http://192.168.1.3/GCM/gcm.php?" + "&regID="+ ID + "&message="+ message; // changes needed here
Log.i("Send URL:", url);
HttpGet request = new HttpGet(url);
response = client.execute(request);
Log.i("responce URL:"," ");
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String webServiceInfo = "";
while ((webServiceInfo = rd.readLine()) != null) {
Log.d("****Status Log***", "Webservice: " + webServiceInfo);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}.execute(null,null,null);
}
// ################################THIS FUNCTION SHOWS DATA FROM THE DATABASE#####################################
public void getTableValues() {
InputStream iss=null;
String line=null;
String result=null;
StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
HttpClient httpClient=new DefaultHttpClient();
HttpPost httpPost=new HttpPost("http://192.168.1.3/retrieve.php");
HttpResponse response=httpClient.execute(httpPost);
HttpEntity entity=response.getEntity();
iss=entity.getContent();
}
catch(ClientProtocolException e)
{
System.out.println("exception 1 caught");
}
catch(IOException e)
{
Log.e("log_tag","ioexception");
e.printStackTrace();
}
try{
BufferedReader reader=new BufferedReader(new InputStreamReader(iss,"iso-8859-1"),8);
StringBuilder sb=new StringBuilder();
while((line=reader.readLine())!=null)
sb.append(line+"\n");
result=sb.toString();
//result now contains the data in the form of json
iss.close();
System.out.println("here is my data");
System.out.println(result);
}
catch(Exception e)
{
System.out.println("exception 2 caught");
}
try{
JSONArray jArray=new JSONArray(result);
int count=jArray.length();
for(int i=0;i<count;i++)
{
JSONObject json_data=jArray.getJSONObject(i);
temp+=json_data.getString("name")+":";
}
//System.out.println(temp);
arr=temp.split(":");
tv.setText(arr[1]);
tv2.setText(arr[2]);
ArrayAdapter my_Adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item,
arr);
My_spinner.setAdapter(my_Adapter);
}
catch(Exception e)
{
System.out.println("m so boread");
//System.out.println("hello");
}
}
//###############################################################################################################
}
// log cat after editing the code as suggested
01-17 21:27:32.939: D/dalvikvm(1895): GC_FOR_ALLOC freed 172K, 3% free 9493K/9692K, paused 3ms, total 3ms
01-17 21:27:33.019: W/EGL_genymotion(1895): eglSurfaceAttrib not implemented
01-17 21:27:33.075: D/AndroidRuntime(1895): Shutting down VM
01-17 21:27:33.075: W/dalvikvm(1895): threadid=1: thread exiting with uncaught exception (group=0xa4be7648)
01-17 21:27:33.075: E/AndroidRuntime(1895): FATAL EXCEPTION: main
01-17 21:27:33.075: E/AndroidRuntime(1895): java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
01-17 21:27:33.075: E/AndroidRuntime(1895): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
01-17 21:27:33.075: E/AndroidRuntime(1895): at java.util.ArrayList.get(ArrayList.java:308)
01-17 21:27:33.075: E/AndroidRuntime(1895): at com.example.gcmclientapp.GcmServer$1.onItemSelected(GcmServer.java:123)
01-17 21:27:33.075: E/AndroidRuntime(1895): at android.widget.AdapterView.fireOnSelected(AdapterView.java:892)
01-17 21:27:33.075: E/AndroidRuntime(1895): at android.widget.AdapterView.access$200(AdapterView.java:49)
01-17 21:27:33.075: E/AndroidRuntime(1895): at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:860)
01-17 21:27:33.075: E/AndroidRuntime(1895): at android.os.Handler.handleCallback(Handler.java:730)
01-17 21:27:33.075: E/AndroidRuntime(1895): at android.os.Handler.dispatchMessage(Handler.java:92)
01-17 21:27:33.075: E/AndroidRuntime(1895): at android.os.Looper.loop(Looper.java:137)
01-17 21:27:33.075: E/AndroidRuntime(1895): at android.app.ActivityThread.main(ActivityThread.java:5103)
01-17 21:27:33.075: E/AndroidRuntime(1895): at java.lang.reflect.Method.invokeNative(Native Method)
01-17 21:27:33.075: E/AndroidRuntime(1895): at java.lang.reflect.Method.invoke(Method.java:525)
01-17 21:27:33.075: E/AndroidRuntime(1895): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
01-17 21:27:33.075: E/AndroidRuntime(1895): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-17 21:27:33.075: E/AndroidRuntime(1895): at dalvik.system.NativeStart.main(Native Method)
Try to populate values into the Spinner, not inside any other method, but inside the onCreate() method. Try to change your program as belows:
Change the getTableValues() method as:
public String[] getTableValues() {
Remove these lines from that method:
ArrayAdapter my_Adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, arr);
My_spinner.setAdapter(my_Adapter);
And return the array "arr" at the end of the method;
return arr;
and then populate values to Spinner at the onCreate() method after initializing the My_spinner object as belows
My_spinner = (Spinner) findViewById(R.id.spinner1);
arr = getTableValues();
ArrayAdapter my_Adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, arr);
My_spinner.setAdapter(my_Adapter);
Try to make this code working as I cannot debug this at the moment. It's a pleasure to help with this...
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class GcmServer extends Activity {
void showToast(CharSequence msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
// declarations for creating the database
SQLiteDatabase mydb;
String name_from_spinner; // this will be used to filter the database for the required registrationID
private static String DBNAME = "new1.db"; // this is our database..change it when you use
private static String TABLE = "MY_TABLE";
//end of dec
EditText et;
String regId,userName;
Button b;
TextView tv,tv2;
String temp="";
String[] arr;
Spinner My_spinner;
InputStream is=null;
ArrayList<String> my_array1 = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gcmserver);
b= (Button)findViewById(R.id.button1);
et=(EditText)findViewById(R.id.editText1);
tv=(TextView)findViewById(R.id.textView1);
tv2=(TextView)findViewById(R.id.textView2);
regId = getIntent().getStringExtra("REGID");
userName = getIntent().getStringExtra("USER");
insertvalues();
My_spinner = (Spinner) findViewById(R.id.spinner1);
List<String> list = getTableValues();
ArrayAdapter my_Adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, list);
My_spinner.setAdapter(my_Adapter);
//setting on click listeners for the items of the spinner
My_spinner.setOnItemSelectedListener(
new OnItemSelectedListener() {
public void onItemSelected(
AdapterView<?> parent, View view, int position, long id) {
name_from_spinner=my_array1.get(position);
showToast(name_from_spinner);// get the name that has been clicked in the spinner
}
public void onNothingSelected(AdapterView<?> parent) {
showToast("Please enter contact");
}
});
// when the send button is clicked,we will extract the message from editText,regID and send to sendtoserver
// send button
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String ID = null;
String REGID=null;
String NAME=null;
String message =et.getText().toString(); //extract message from edit text
// extract registration number
try {
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
Cursor allrows = mydb.rawQuery("SELECT * FROM " + TABLE, null);
if (allrows.moveToFirst()) {
do {
ID = allrows.getString(0);
REGID = allrows.getString(1);
NAME = allrows.getString(2);
if(NAME.equals(name_from_spinner)) // string comparison
{
break;
}
} while (allrows.moveToNext());
showToast("left loop");
}
allrows.close();
mydb.close();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Error encountered.",
Toast.LENGTH_LONG);
}
//tv.setText(REGID);
System.out.print(REGID);
sendToServer(message,REGID);
}
});
}
//#########################################INSERT############################################################
public void insertvalues()
{
StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("regid", regId));
nameValuePairs.add(new BasicNameValuePair("name", userName));
try {
//tv2.setText(regId);
HttpClient httpClient=new DefaultHttpClient();
HttpPost httpPost=new HttpPost("http://192.168.1.3/new.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response=httpClient.execute(httpPost);
HttpEntity entity=response.getEntity();
is=entity.getContent();
showToast("data inserted successfully");
}
catch(ClientProtocolException e)
{
Log.e("clientProtocol","Log_tag");
e.printStackTrace();
}catch(IOException e)
{
Log.e("log_tag","ioexception");
e.printStackTrace();
}
}
public void sendToServer(final String message,final String ID){
//tv2.setText(ID);
new AsyncTask<String, Void, String>(){
// changes are needed here
#Override
protected String doInBackground(String... params) {
try {
HttpResponse response = null;
HttpParams httpParameters = new BasicHttpParams();
HttpClient client = new DefaultHttpClient(httpParameters);
String url="http://192.168.1.3/GCM/gcm.php?" + "&regID="+ ID + "&message="+ message; // changes needed here
Log.i("Send URL:", url);
HttpGet request = new HttpGet(url);
response = client.execute(request);
Log.i("responce URL:"," ");
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String webServiceInfo = "";
while ((webServiceInfo = rd.readLine()) != null) {
Log.d("****Status Log***", "Webservice: " + webServiceInfo);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}.execute(null,null,null);
}
// ################################THIS FUNCTION SHOWS DATA FROM THE DATABASE#####################################
public List<String> getTableValues() {
InputStream iss=null;
String line=null;
String result=null;
StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
HttpClient httpClient=new DefaultHttpClient();
HttpPost httpPost=new HttpPost("http://192.168.1.3/retrieve.php");
HttpResponse response=httpClient.execute(httpPost);
HttpEntity entity=response.getEntity();
iss=entity.getContent();
}
catch(ClientProtocolException e)
{
System.out.println("exception 1 caught");
}
catch(IOException e)
{
Log.e("log_tag","ioexception");
e.printStackTrace();
}
try{
BufferedReader reader=new BufferedReader(new InputStreamReader(iss,"iso-8859-1"),8);
StringBuilder sb=new StringBuilder();
while((line=reader.readLine())!=null)
sb.append(line+"\n");
result=sb.toString();
//result now contains the data in the form of json
iss.close();
System.out.println("here is my data");
System.out.println(result);
}
catch(Exception e)
{
System.out.println("exception 2 caught");
}
List<String> list = new ArrayList<String>();
try{
JSONArray jArray=new JSONArray(result);
int count=jArray.length();
for(int i=0;i<count;i++)
{
JSONObject json_data=jArray.getJSONObject(i);
list.add(json_data.getString("name"));
}
//System.out.println(temp);
tv.setText(arr[1]);
tv2.setText(arr[2]);
}
catch(Exception e)
{
System.out.println("m so boread");
//System.out.println("hello");
}
return list;
}
//###############################################################################################################
}

How to display image from mysql database?

I have code to display all data from MySQL databae also i have a image field in MySQL database which have image names.how can i display image from database(The image is located at localhost folder). Im new in android so please help me. Here is my code if u can alter my required code then it will be a great help.
JAVA
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class News_events extends Fragment {
private String jsonResult;
private String url = "http://192.168.2.7/crescentnews/select.php";
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
InputStream is=null;
String result=null;
String line=null;
int code;
public News_events(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_news_events, container, false);
accessWebService();
return rootView;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
display();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void display() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("news_details");
LinearLayout MainLL= (LinearLayout)getActivity().findViewById(R.id.newslayout);
//LinearLayout headLN=(LinearLayout)findViewById(R.id.headsection);
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
final String head = jsonChildNode.optString("title");
final String details = jsonChildNode.optString("text");
final String date = jsonChildNode.optString("date");
//final String time = jsonChildNode.optString("time");
TextView headln = new TextView(this.getActivity());
headln.setText(head); // News Headlines
headln.setTextSize(20);
headln.setTextColor(Color.BLACK);
headln.setGravity(Gravity.CENTER);
headln.setBackgroundResource(R.drawable.menubg);
headln.setPadding(10, 20, 10, 0);
headln.setWidth(100);
headln.setClickable(true);
headln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(getBaseContext(), head, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity().getApplicationContext(),MainActivity.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
ImageView photo=new ImageView(this.getActivity());
//dateln.setBackgroundColor(Color.parseColor("#f20056"));
photo.setBackgroundColor(Color.parseColor("#000000"));
photo.setPadding(0, 0, 10, 10);
photo.setClickable(true);
TextView dateln = new TextView(this.getActivity());
dateln.setText(date); // News Headlines
dateln.setTextSize(12);
dateln.setTextColor(Color.BLACK);
dateln.setGravity(Gravity.RIGHT);
//dateln.setBackgroundColor(Color.parseColor("#f20056"));
dateln.setBackgroundColor(0x00000000);
dateln.setPadding(0, 0, 10, 10);
dateln.setWidth(100);
dateln.setClickable(true);
dateln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(), MainActivity.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
View sep=new View(this.getActivity());
sep.setBackgroundColor(Color.parseColor("#252525"));
sep.setMinimumHeight(10);
TextView detailsln = new TextView(this.getActivity());
detailsln.setText(details); // News Details
detailsln.setTextSize(12);
detailsln.setTextColor(Color.BLACK);
detailsln.setGravity(Gravity.LEFT);
detailsln.setPadding(10, 10, 10, 10);
MainLL.addView(headln);
MainLL.addView(dateln);
MainLL.addView(photo);
MainLL.addView(detailsln);
MainLL.addView(sep);
detailsln.setClickable(true);
detailsln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(), MainActivity.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
}
} catch (JSONException e) {
Toast.makeText(getActivity().getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
}
}
save your image url in db (if they are in a same folder on your host choose a base url and save only image name)
after fetching your data , there are alot of library for display images such as :
Picasso
A powerful image downloading and caching library for Android

using AsyncTask i want the data in list view when calling restful api

I just build a demo application through async task and now i want the json data in list view so i dont know where i can add json functions and array list etc so plz guide me or help me by edit the code i thankful in advance and plz help im new to android and java
package your.packag.namespace;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class runActivity extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://192.168.1.156/recess/document/document");
HttpClient client = new DefaultHttpClient();
HttpResponse response=null;
try{
response = client.execute(httpGet);}
catch(Exception e){}
System.out.println(response.getStatusLine());
String text = null;
try {
response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results!=null) {
EditText et = (EditText)findViewById(R.id.my_edit);
et.setText(results);
}
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(true);
}
}}
You can use the built-in org.json classes to convert the retrieved string (your text variable content) in to JSON objects.
Have a look at the tutorial from Lars Vogel on how to do that.

android text not visible

I am sending some information from my application to server and waiting for the response. Before i send i set my textview for message to display "processing request" and after getting response i display a different message.
This processing message is not getting displayed. Is it beacuse the UI is getting blocked due to other operation.
How to handle this. Threading is not giving correct result as need to display the response.
SO that involve UI in the thread .
package com.PandG.app.android.activities;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.PandG.app.android.R;
import com.PandG.app.android.dataAccess.SettingsDBAccess;
import com.PandG.app.android.entity.Job;
import com.PandG.app.android.entity.Settings;
import com.PandG.app.android.services.JobsManager;
import com.lib.android.Utils.Utils;
import com.lib.android.activity.BaseActivity;
import com.lib.android.dataAccess.DatabaseManager;
public class JobCheckoutActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setViewContent();
}
private void setViewContent() {
Settings setting = getSettings();
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.job_checkout);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.customtitle);
//new DataProcess().execute(null);
TextView text1 = (TextView)findViewById(R.id.checkoutmessage);
text1.setText("Processiong Job Cart ...");
if(setting!=null){
TextView text2 = (TextView)findViewById(R.id.checkoutheading);
text2.setVisibility(View.GONE);
Button homeButton = (Button)findViewById(R.id.gohome);
homeButton.setVisibility(View.GONE);
JSONObject jobObject =encodeData(setting);
sendDataToServer(jobObject);
}
}
private void sendDataToServer(JSONObject jobObject) {
TextView text1 = (TextView)findViewById(R.id.checkoutmessage);
text1.setText("Processiong Job Cart ...");
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
// Limit
HttpResponse response;
try {
HttpPost post = new HttpPost(Utils.getPostUrl());
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("orderparameters",
jobObject.toString()));
Log.i("Job ORDER", jobObject.toString());
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = client.execute(post);
checkResponseFromServer(response);
ClearCart();
} catch (Exception e) {
Log.w("error", "connection failed");
Toast.makeText(this, "Order not placed due to connection error",
Toast.LENGTH_LONG);
e.printStackTrace();
}
}
private void ClearCart() {
JobsManager.JobsCartList.clear();
}
private void checkResponseFromServer(HttpResponse response) {
try {
if (response != null) {
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
in.close();
JSONObject jsonResponse = new JSONObject(buffer.toString());
Log.i("Status", jsonResponse.getString("status"));
Log.i("Status", jsonResponse.getString("message"));
Log.i("Status", jsonResponse.getString("debug"));
TextView text1 = (TextView)findViewById(R.id.checkoutheading);
text1.setVisibility(View.VISIBLE);
TextView text = (TextView) findViewById(R.id.checkoutmessage);
if (jsonResponse.getString("status").equals("SUCC")) {
text.setText( Html.fromHtml(getString(R.string.checkout_body1)));
} else
text.setText(jsonResponse.getString("message")
+ jsonResponse.getString("debug"));
}
} catch (Exception ex) {
}
}
private JSONObject encodeData(Settings setting) {
JSONObject jobObject = new JSONObject();
try {
JSONObject jobject = new JSONObject();
jobject.put("name", setting.getName());
jobject.put("email", setting.getEmail());
jobject.put("phone", setting.getPhone());
jobject.put("school", setting.getSchool());
jobject.put("major", setting.getMajor());
jobObject.put("customer", jobject);
JSONArray jobsarray = new JSONArray();
for (Job job : JobsManager.JobsCartList) {
JSONObject jobEntry = new JSONObject();
jobEntry.put("jobtitle",job.getTitle());
jobEntry.put("qty","1");
jobsarray.put(jobEntry);
}
jobObject.put("orders", jobsarray);
} catch (JSONException ex) {
}
return jobObject;
}
private Settings getSettings() {
SettingsDBAccess settingsDBAccess = new SettingsDBAccess(
DatabaseManager.getInstance());
Settings setting = settingsDBAccess.getSetting();
if (setting==null){
startActivityForResult((new Intent(this,SettingsActivity.class)),Utils
.getDefaultRequestCode());
}
return setting;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Settings setting = new SettingsDBAccess(
DatabaseManager.getInstance()).getSetting();
if(setting!=null){
JSONObject jobObject = encodeData(setting);
sendDataToServer(jobObject);
}
}
/* private class DataProcess extends AsyncTask {
#Override
protected void onPostExecute(Object result) {
}
#Override
protected Object doInBackground(Object... arg0) {
processDataandsend();
return null;
}
private void processDataandsend() {
Settings setting = getSettings();
if(setting!=null){
TextView text2 = (TextView)findViewById(R.id.checkoutheading);
text2.setVisibility(View.GONE);
Button homeButton = (Button)findViewById(R.id.gohome);
homeButton.setVisibility(View.GONE);
JSONObject jobObject =encodeData(setting);
sendDataToServer(jobObject);
}
}
} */
}
You should not perform HTTP-work on the UI-thread. Instead use AsyncTask
In your AsyncTask you are only allowed to update the UI in two places:
#Override
protected void onPreExecute()
TextView.setText("Beginning HTTP-work..Please wait");
{
and
#Override
protected void onPostExecute(Void v) {
TextView.setText("Done..SUCCESS!");
}
Use these two to update the UI before and after the HTTP-work has been done.
Long operations must be in background. Best way to implement this on Android, use AsyncTask, for more information: http://developer.android.com/reference/android/os/AsyncTask.html

Categories

Resources