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?" + "®ID="+ 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?" + "®ID="+ 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;
}
//###############################################################################################################
}
Related
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);
}
Hello guys so i'm having difficult in changing this classes that i've created to httpurlConnection. i've seraced the web and im not familiar at all with the httpUrlConnection
App flow:
coming to MainActivity => OnTokenAcuired => GetCokie => Auth
then i have an httpPostRequest
MainActivity:
package com.ap2.demo.comunication;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import com.ap2.demo.R;
import com.ap2.demo.general.SplashActivity;
import org.apache.http.impl.client.DefaultHttpClient;
import java.util.ArrayList;
public class MainActivity extends Activity {
AccountManager accountManager;
private Account[] accounts;
Spinner spinner;
public static DefaultHttpClient httpClient = new DefaultHttpClient();
Account account;
public static String email = "";
ImageView img;
public static boolean enteredOnce = false;
public static String uniqueIDPhone = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
accountManager = AccountManager.get(getApplicationContext());
// assembling all gmail accounts
accounts = accountManager.getAccountsByType("com.google");
// add all gmail accounts :
ArrayList<String> accountList = new ArrayList<String>();
for (Account account : accounts) {
accountList.add(account.name);
}
// setting spinner to be viewed
spinner = (Spinner) findViewById(R.id.account);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, accountList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
img = (ImageView) findViewById(R.id.splash_door);
//Button startAuth = (Button) findViewById(R.id.startAuth);
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
spinner = (Spinner) findViewById(R.id.account);
account = accounts[spinner.getSelectedItemPosition()];
email = account.name;
// getIntent().putExtra("task", 1);
accountManager.getAuthToken(account, "ah", null, false,
new OnTokenAcquired(httpClient, MainActivity.this), null);
Intent intent = new Intent(MainActivity.this, SplashActivity.class);
startActivity(intent);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK) {
accountManager.getAuthToken(account, "ah", null, false,
new OnTokenAcquired(httpClient, MainActivity.this), null);
}
else if(resultCode == RESULT_CANCELED){
// user canceled
}
}
}
OnTokenAcquired:
package com.ap2.demo.comunication;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import com.ap2.demo.enumPackage.Constants;
import org.apache.http.impl.client.DefaultHttpClient;
/**
* Created by Daniel on 19-Jun-15.
*/
/*the result for the auth token request is returned to your application
via the Account Manager Callback you specified when making the request.
check the returned bundle if an Intent is stored against the AccountManager.KEY_INTENT key.
if there is an Intent then start the activity using that intent to ask for user permission
otherwise you can retrieve the auth token from the bundle.*/
public class OnTokenAcquired implements AccountManagerCallback<Bundle> {
private static final int USER_PERMISSION = 989;
private DefaultHttpClient httpclient;
Activity activity;
public OnTokenAcquired(DefaultHttpClient httpclient, Activity activity)
{
this.httpclient = httpclient;
this.activity = activity;
}
#Override
public void run(AccountManagerFuture<Bundle> result) {
Bundle bundle;
try {
bundle = (Bundle) result.getResult();
if (bundle.containsKey(AccountManager.KEY_INTENT)) {
Intent intent = bundle.getParcelable(AccountManager.KEY_INTENT);
intent.setFlags(intent.getFlags() & ~Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivityForResult(intent, USER_PERMISSION);
} else {
setAuthToken(bundle);
}
}
catch(Exception e){
e.printStackTrace();
}
}
//using the auth token and ask for a auth cookie
protected void setAuthToken(Bundle bundle) {
String authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
new GetCookie(httpclient, Constants.SERVER_REQUESTS.MY_APP_ID, activity.getBaseContext()).execute(authToken);
}
}
package com.ap2.demo.comunication;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import com.ap2.demo.enumPackage.Constants;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;
import java.io.ByteArrayOutputStream;
/**
* Created by Daniel on 19-Jun-15.
*/
public class GetCookie extends AsyncTask<String, Void, Boolean> {
String appId;
HttpParams params;
private HttpResponse response;
Context context;
private DefaultHttpClient httpclient;
public GetCookie(DefaultHttpClient httpclient, String appId, Context context)
{
this.httpclient = httpclient;
params = httpclient.getParams();
this.appId = appId;
this.context = context;
}
protected Boolean doInBackground(String... tokens) {
try {
// Don't follow redirects
params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);
HttpGet httpGet = new HttpGet("http://" + appId
+ ".appspot.com/_ah/login?continue=http://" + appId + ".appspot.com/&auth=" + tokens[0]);
response = httpclient.execute(httpGet);
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
if(response.getStatusLine().getStatusCode() != 302){
// Response should be a redirect
return false;
}
//check if we received the ACSID or the SACSID cookie, depends on http or https request
for(Cookie cookie : httpclient.getCookieStore().getCookies()) {
if(cookie.getName().equals("ACSID") || cookie.getName().equals("SACSID")){
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
cancel(true);
} finally {
params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
}
return false;
}
protected void onPostExecute(Boolean result)
{
new Auth(httpclient, context).execute(Constants.SERVER_REQUESTS.LOGIN);
}
}
package com.ap2.demo.comunication;
import android.content.Context;
import android.os.AsyncTask;
import android.telephony.TelephonyManager;
import android.widget.Toast;
import com.ap2.demo.R;
import com.ap2.demo.enumPackage.Constants;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
/**
* Created by Daniel on 19-Jun-15.
*/
public class Auth extends AsyncTask<String, Void, Boolean> {
private DefaultHttpClient httpclient;
private HttpResponse response;
private String content = null;
Context context;
public Auth(DefaultHttpClient httpclient, Context context)
{
this.httpclient = httpclient;
this.context = context;
}
protected Boolean doInBackground(String... urls) {
try {
HttpGet httpGet = new HttpGet(urls[0]);
response = httpclient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
content = out.toString();
return true;
}
} catch (Exception e) {
e.printStackTrace();
cancel(true);
}
return false;
}
//display the response from the request above
protected void onPostExecute(Boolean result) {
if (content != null) {
try {
System.out.print(result);
JSONObject obj = new JSONObject(content);
String status = obj.getString(Constants.LOGIN_SERVICE.STATUS);
if (status.equals(Constants.LOGIN_SERVICE.LOGIN_STATUS_OF_USER)) {
Toast.makeText(context, R.string.user_already_logged_in_status,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, R.string.welcome_message,
Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(context, R.string.failed_to_login + content,
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(context, R.string.could_not_loged_to_server,
Toast.LENGTH_LONG).show();
}
}
}
now notice im using the same httpclient because of the auth and cockie:
package com.ap2.demo.channels;
import android.app.Activity;
import android.os.AsyncTask;
import com.ap2.demo.comunication.MainActivity;
import com.ap2.demo.enumPackage.Constants;
import com.ap2.demo.main_activity.MapWithMarkers;
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.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Daniel on 30-Jun-15.
*/
public class ServerRequestAddChannel extends AsyncTask<String, String, String> {
Activity activity;
String name;
public ServerRequestAddChannel(Activity activity, String name) {
this.activity = activity;
this.name = name;
}
#Override
protected String doInBackground(String... params) {
HttpPost httppost = new HttpPost(params[0]);
try {
// i have name and path only left id
int idCounter = MapWithMarkers.id_counter++;
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
String name_of_channel = name;
if (name.equals(Constants.REVIEWS_CHANNEL.NAME)) {
// add special id to reviews channel
nameValuePairs.add(new BasicNameValuePair(Constants.REVIEWS_CHANNEL.ID, Constants.REVIEWS_CHANNEL.ID));
} else {
name_of_channel = name + Integer.toString(idCounter);
// taking off all free space for unique id
name_of_channel = name_of_channel.replaceAll(" ","");
nameValuePairs.add(new BasicNameValuePair(Constants.CHANNEL_REQUESTS.CHANNEL_TAG_ID, name_of_channel));
}
nameValuePairs.add(new BasicNameValuePair(Constants.CHANNEL_REQUESTS.CHANNEL_TAG_NAME, name));
nameValuePairs.add(new BasicNameValuePair(Constants.CHANNEL_REQUESTS.CHANNEL_TAG_ICON, ""));
// adding the channel to my new list
if (!name_of_channel.equals(Constants.REVIEWS_CHANNEL.NAME)) {
MapWithMarkers.channels_map.put(name_of_channel, new ChannelItem(name_of_channel, "", name));
MapWithMarkers.my_subscriptions.add(name_of_channel);
}
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = MainActivity.httpClient.execute(httppost);
HttpEntity entity = response.getEntity();
String text = getASCIIContentFromEntity(entity);
return response.getStatusLine().getReasonPhrase().toString();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return null;
}
protected void onPostExecute(String result) {
((AddChannelActivity) activity).moveToNextIntent();
}
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();
}
}
please help..
I'm working on an Android app that uses spinner and was connected to a MySQL server, but it seems that the dropdown list is not showing on the spinner.
package edu.sti.mobileinstructorevaluation;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
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 java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class MainActivity extends ActionBarActivity {
ArrayList<String> listItems=new ArrayList<>();
ArrayAdapter<String> adapter;
Spinner sp;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp=(Spinner)findViewById(R.id.spinner);
adapter=new ArrayAdapter<String>(this,R.layout.spinner_layout,R.id.txt,listItems);
sp.setAdapter(adapter);
}
public void onStart(){
super.onStart();
BackTask bt=new BackTask();
bt.execute();
}
private class BackTask extends AsyncTask<Void,Void,Void> {
ArrayList<String> list;
protected void onPreExecute(){
super.onPreExecute();
list=new ArrayList<>();
}
protected Void doInBackground(Void...params){
InputStream is=null;
String result="";
try{
HttpClient httpclient=new DefaultHttpClient();
HttpPost httppost= new HttpPost("http://10.0.2.2:8080/mobieva/getcourse.php");
HttpResponse response=httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
}catch(IOException e){
e.printStackTrace();
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
String line = null;
while ((line = reader.readLine()) != null) {
result+=line;
}
is.close();
//result=sb.toString();
}catch(Exception e){
e.printStackTrace();
}
// parse json data
try{
JSONArray jArray =new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject jsonObject=jArray.getJSONObject(i);
// add interviewee name to arraylist
list.add(jsonObject.getString("cname"));
}
}
catch(JSONException e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result){
listItems.addAll(list);
adapter.notifyDataSetChanged();
}
}
}
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
Hy!!
I have a problem with the progressdialog.
My used code:
package com.android.skiptvad;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
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.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.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.LightingColorFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.skiptvad.*;
public class Login extends Activity {
/** Called when the activity is first created. */
TextView tvuser;
String sessionid;
ProgressDialog pd = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
tvuser = (TextView) findViewById(R.id.tvuser);
TextView tvpw = (TextView) findViewById(R.id.tvpw);
final EditText etuser = (EditText) findViewById(R.id.etuser);
final EditText etpw = (EditText) findViewById(R.id.etpw);
Button btlogin = (Button)findViewById(R.id.btlogin);
btlogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (etuser.getText() != null && etpw.getText()!= null)
{
runOnUiThread(new Runnable() {
#Override
public void run() {
pd = ProgressDialog.show(Login.this,"","Loading. Please wait...", true);
pd.show();
Thread t = new Thread() {
public void run(){
download(etuser.getText().toString(), md5(etpw.getText().toString()));
pd.dismiss();
}
};
t.run();
}
});
}
}
});
}
public void download (final String user, final String pw)
{
try{
HttpClient client = new DefaultHttpClient();
String postURL = "link_deleted";
HttpPost post = new HttpPost(postURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", user));
params.add(new BasicNameValuePair("password", pw));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
final JSONObject jObject = new JSONObject(EntityUtils.toString(resEntity));
JSONObject menuObject = jObject.getJSONObject("responseData");
if (jObject.getInt("responseStatus")== 200 && jObject.get("responseDetails")!= null)
{
sessionid = menuObject.getString("session_id");
finish();
}
else
{
//dismissDialog(DIALOG_LOADING);
if (jObject.getInt("responseStatus")== 500)
{
throw new Exception("Server Error");
}
else if (jObject.getInt("responseStatus")== 400)
{
throw new Exception("Wrong User/Password");
}
else
{
throw new Exception();
}
}
//pd.dismiss();
} catch (Exception e) {
//dismissDialog(DIALOG_LOADING);
Toast toast ;
toast = Toast.makeText(getApplicationContext(), e.getMessage(), 500);
toast.show();
}
}
private String md5(String in) {
MessageDigest digest;
try {
digest = MessageDigest.getInstance("MD5");
digest.reset();
digest.update(in.getBytes());
byte[] a = digest.digest();
int len = a.length;
StringBuilder sb = new StringBuilder(len << 1);
for (int i = 0; i < len; i++) {
sb.append(Character.forDigit((a[i] & 0xf0) >> 4, 16));
sb.append(Character.forDigit(a[i] & 0x0f, 16));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) { e.printStackTrace(); }
return null;
}
}
No error occurs in the Dalvik Debug Monitor.
Please help
I would recommend to use AsyncTask for this case. So in your AsyncTask.onPreExecute() you call Activity.showDialog(int id), do your networking job in AsyncTask.doInBackground() and Activity.dismissDialog(int id) the dialog in AsyncTask.onPostExecute().
I think that's the most correct way of doing such "under-popup" things.