I am new to android app development, and one of my clients asked me to fix this code his past dev left the job . there were a lot of errors I was able to fix it. But now I am stuck at a point in HTTP request error in java and cannot execute this code. Let me know how to fix it. Current status complied SDK 33 and cannot downgrade the same. Code below. HTTP client is deprecated.
package com.ecom.ecommerce;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.TextView;
public class ActivityCategoryList extends Activity {
GridView listCategory;
ProgressBar prgLoading;
TextView txtAlert;
// declare adapter object to create custom category list
AdapterCategoryList cla;
// create arraylist variables to store data from server
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
String CategoryAPI;
int IOConnect = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_list);
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new
ColorDrawable(getResources().getColor(R.color.header)));
bar.setDisplayHomeAsUpEnabled(true);
bar.setHomeButtonEnabled(true);
bar.setTitle("Category");
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
listCategory = (GridView) findViewById(R.id.listCategory);
txtAlert = (TextView) findViewById(R.id.txtAlert);
cla = new AdapterCategoryList(ActivityCategoryList.this);
// category API url
CategoryAPI = Constant.CategoryAPI+"?accesskey="+Constant.AccessKey;
// call asynctask class to request data from server
new getDataTask().execute();
// event listener to handle list when clicked
listCategory.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
// go to menu page
Intent iMenuList = new Intent(ActivityCategoryList.this, ActivityMenuList.class);
iMenuList.putExtra("category_id", Category_ID.get(position));
iMenuList.putExtra("category_name", Category_name.get(position));
startActivity(iMenuList);
overridePendingTransition(R.anim.open_next, R.anim.close_next);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_category, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.cart:
// refresh action
Intent iMyOrder = new Intent(ActivityCategoryList.this, ActivityCart.class);
startActivity(iMyOrder);
overridePendingTransition (R.anim.open_next, R.anim.close_next);
return true;
case R.id.refresh:
IOConnect = 0;
listCategory.invalidateViews();
clearData();
new getDataTask().execute();
return true;
case android.R.id.home:
// app icon in action bar clicked; go home
this.finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// clear arraylist variables before used
void clearData(){
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
// asynctask class to handle parsing json in background
public class getDataTask extends AsyncTask<Void, Void, Void>{
// show progressbar first
getDataTask(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// when finish parsing, hide progressbar
prgLoading.setVisibility(8);
// if internet connection and data available show data on list
// otherwise, show alert text
if((Category_ID.size() > 0) && (IOConnect == 0)){
listCategory.setVisibility(0);
listCategory.setAdapter(cla);
}else{
txtAlert.setVisibility(0);
}
}
}
// method to parse json data from server
public void parseJSONData(){
clearData();
try {
// request data from Category API
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(CategoryAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}
// parse json data and store into arraylist variables
JSONObject json = new JSONObject(str);
JSONArray data = json.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject object = data.getJSONObject(i);
JSONObject category = object.getJSONObject("Category");
Category_ID.add(Long.parseLong(category.getString("Category_ID")));
Category_name.add(category.getString("Category_name"));
Category_image.add(category.getString("Category_image"));
Log.d("Category name", Category_name.get(i));
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
//cla.imageLoader.clearCache();
listCategory.setAdapter(null);
super.onDestroy();
}
#Override
public void onConfigurationChanged(final Configuration newConfig)
{
// Ignore orientation change to keep activity from restarting
super.onConfigurationChanged(newConfig);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
}
}
Related
Been trying to write an app in android studio. Part of the app has to parse a document in JSON and display two TextViews of data for each instance. One being Signal and the other being Noise. I am trying to make a custom list view in case I want to add more detail to each instance. I also would like to make it all contained in a ScrollView. I initially had no problems parsing the document but now that I am trying to implement the ListAdapter I am running into issues.
My code is giving me the error...
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.yesinc.tsi880, PID: 4919
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.yesinc.tsi880.TelemetryActivity$JSONTask.onPostExecute(TelemetryActivity.java:136)
at com.yesinc.tsi880.TelemetryActivity$JSONTask.onPostExecute(TelemetryActivity.java:50)
Not sure if the problem is with the document that I am trying to parse or the java code itself. Any help would be much appreciated. Code is below.
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.yesinc.tsi880.models.SondeModel;
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.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import android.widget.ArrayAdapter;
public class TelemetryActivity extends AppCompatActivity {
private TextView tvData;
private ListView lvSondes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_telemetry);
ListView lvSondes = findViewById(R.id.lvSondes);
//new JSONTask().execute("http://172.16.5.70/plots/sigstr2.txt");
}
public class JSONTask extends AsyncTask<String, String, List<SondeModel> >{
#Override
protected List<SondeModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line;
while((line=reader.readLine()) != null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONObject parentArray0 = parentObject.getJSONObject("0");
JSONObject parentArray1 = parentObject.getJSONObject("1");
List<SondeModel> sondeModelList = new ArrayList<>();
//StringBuffer finalBufferedData = new StringBuffer();
for(int i=0; i<8; i++){
String sonde = String.valueOf(i);
JSONObject finalObject = parentArray0.getJSONObject(sonde);
SondeModel sondeModel = new SondeModel();
sondeModel.setNoisedbm(finalObject.getString("noisedbm"));
sondeModel.setSigdbm(finalObject.getString("sigdbm"));
//String noiseDBM = finalObject.getString("noisedbm");
//String sigDBM = finalObject.getString("sigdbm");
sondeModelList.add(sondeModel);
}
for(int i=0; i<8; i++){
String sonde = String.valueOf(i);
JSONObject finalObject = parentArray1.getJSONObject(sonde);
SondeModel sondeModel = new SondeModel();
sondeModel.setNoisedbm(finalObject.getString("noisedbm"));
sondeModel.setSigdbm(finalObject.getString("sigdbm"));
//String noiseDBM = finalObject.getString("noisedbm");
//String sigDBM = finalObject.getString("sigdbm");
sondeModelList.add(sondeModel);
}
return sondeModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection != null) {
connection.disconnect();
}try {
if(reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<SondeModel> result) {
super.onPostExecute(result);
SondeAdapter adapter = new SondeAdapter(getApplicationContext(), R.layout.row, result);
lvSondes.setAdapter(adapter);
// TODO need to set a data to the List
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.navigation, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.navigation_telemetry) {
new JSONTask().execute("http://172.16.5.70/plots/sigstr2.txt");
return true;
}
return super.onOptionsItemSelected(item);
}
public class SondeAdapter extends ArrayAdapter{
public List<SondeModel> sondeModelList;
private int resource;
private LayoutInflater inflater;
public SondeAdapter(Context context, int resource, List<SondeModel> objects) {
super(context, resource, objects);
sondeModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = inflater.inflate(resource, null);
}
TextView sig;
TextView noise;
sig = (TextView)convertView.findViewById(R.id.sig);
noise = (TextView)convertView.findViewById(R.id.noise);
sig.setText(sondeModelList.get(position).getSigdbm());
noise.setText(sondeModelList.get(position).getNoisedbm());
return convertView;
}
}
}
ListView lvSondes = findViewById(R.id.lvSondes);
You are re-declaring the lvSondes inside your onCreate method. The class member list view is never used and is never initialized. Instead a local lvSondes is initialized. This variable will not be in scope and won't be visible to the AsyncTask. The async task will use the member variable and that will be null.
Solution: remove the ListView from the stated line and just initialize the member variable
It's hours I search for something, but it doesn't seem to help.. Android Studio doesn't launch any error, but the screen remains blank. Why?
package org.newapp;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import saxrssreader.*;
public class MainActivity extends Activity {
private ArrayAdapter<RssItem> rssItemsArrayAdapter;
ListView codeLearnLessons;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RssItem[] rssItems = new RssItem[]{};
rssItemsArrayAdapter = new ArrayAdapter<RssItem>(this, android.R.layout.simple_list_item_1, rssItems);
new WebCall().execute(rssItems);
codeLearnLessons = (ListView)findViewById(R.id.listView1);
codeLearnLessons.setAdapter(rssItemsArrayAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
private class WebCall extends AsyncTask<RssItem, Void, Void> {
#Override
protected Void doInBackground(RssItem... items) {
URL url = null;
try {
url = new URL("http://www.somewpsite.com/feed");
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
ArrayList<RssItem> listItems = RssReader.read(url).getRssItems();
items = listItems.toArray(new RssItem[listItems.size()]);
final int l = items.length;
runOnUiThread(new Runnable() {
#Override
public void run() {
codeLearnLessons.invalidateViews();
rssItemsArrayAdapter.notifyDataSetChanged();
Log.i("rec", "rec" + l);
}
});
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
/*ProgressDialog mDialog = new ProgressDialog(MainActivity.this);
mDialog.setMessage("Please wait...");
mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mDialog.setIndeterminate(true);
mDialog.setCancelable(false);
mDialog.show();*/
}
}
}
The issue is that your using a ArrayList which only has scope inside of the AsyncTask.doInBackground() method. Since it is not given to the adapter, the notifyDataSetChanged() does nothing. You'll need to replace the existing array like this:
rssItemsArrayAdapter.clear();
rssItemsArrayAdapter.addAll(listItems);
rssItemsArrayAdapter.notifyDataSetChanged();
Having said that, you also really need to change your use of AsyncTask. There's no need to call runOnUiThread() from within your doInBackground() as the AsyncTask will automatically run its onPostExecute() on the UI thread. Have your doInBackground() method return your new ArrayList<RssItem> and create an onPostExecute() override method which adjusts the adapter as shown above.
You are passing your items to the AsyncTask but in the AsyncTask you declare them new with the content of your result. You never pass the items to your ArrayAdapter back. Make them a property of your class instance.
Edit - Example:
rssItemsArrayAdapter.clear();
rssItemsArrayAdapter.addAll(items);
and afterwards
rssItemsArrayAdapter.notifyDataSetChanged();
I have the following code which is working without any errors, but I get this
Skipped 116 frames. The application may be doing too much work on its main thread.
That happens when I press the Single button and the init() method is executed.
How can I execute the method in another thread so it won't break like that ?
package com.apppppp.pampam;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Set;
import android.support.v7.app.ActionBarActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.ParcelUuid;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
Button singleButton;
BluetoothAdapter mBluetoothAdapter;
BluetoothAdapter blueAdapter ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
blueAdapter = BluetoothAdapter.getDefaultAdapter();
singleButton = (Button) findViewById(R.id.button1);
setButtonOnClickListeners();
return true;
}
private void setButtonOnClickListeners(){
singleButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
try {
write("Salut");
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("No luck");
}
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private OutputStream outputStream;
private InputStream inStream;
private void init() throws IOException {
if (blueAdapter != null) {
if (blueAdapter.isEnabled()) {
Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();
System.out.println(bondedDevices);
if(bondedDevices.size() > 0){
Iterator iter = bondedDevices.iterator();
BluetoothDevice device = (BluetoothDevice) iter.next();
ParcelUuid[] uuids = device.getUuids();
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
socket.connect();
outputStream = socket.getOutputStream();
inStream = socket.getInputStream();
}
else{
Log.e("error", "No appropriate paired devices.");
}
}else{
Log.e("error", "Bluetooth is disabled.");
}
}
}
public void write(String s) throws IOException{
init();
outputStream.write(s.getBytes());
}
public void run() {
final int BUFFER_SIZE = 1024;
byte[] buffer = new byte[BUFFER_SIZE];
int bytes = 0;
int b = BUFFER_SIZE;
while (true) {
try {
bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Thank you
You are doing the Bluetooth related calls on the UI thread and you blocking the UI thread with these calls.
When I try to write the file, it does not want to write a new file. The FileNotFoundException occurs when the app tries to write to the file. I have seen this code working here: https://www.youtube.com/watch?v=YzwiuRDgSSY
package com.example.serialization;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.util.UUID;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
TextView label;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Person arthur = new Person();
arthur.name = "Arthur Dent";
arthur.age = 44;
label = (TextView) findViewById(R.id.textView1);
label.setText("Nothing here");
String fileName = "data.txt";
try {
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(fileName));
os.writeObject(arthur);
os.close();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
label.setText("File not found");
}
catch (IOException e) {
// TODO Auto-generated catch block
label.setText("IOException");
e.printStackTrace();
}
try {
ObjectInputStream is = new ObjectInputStream(new FileInputStream(fileName));
Person p = (Person) is.readObject(); // read object
label.setText("Show name: " + p.name + " Show age: " + p.age);
is.close();
}
catch (StreamCorruptedException e) {
label.setText("Stream corrupted");
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (FileNotFoundException e) {
label.setText("File not found 2");
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
label.setText("IOException");
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClassNotFoundException e) {
label.setText("Class not found");
// TODO Auto-generated catch block
e.printStackTrace();
}
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
Person.java
package com.example.serialization;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Person implements Serializable{
/**
*
*/
private static final long serialVersionUID = 2794858669568274884L;
public String name;
public int age;
//streams are not Serializable
public ObjectOutputStream os;
}
Try this:
File outputFile = new File(getFilesDir(), fileName);
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(outputFile));
os.writeObject(arthur);
The example video is for desktop java, where you can normally write files without specifying a path. However on Android you should always specify one - you can use internal storage or external storage. Here's the Android guide on how to write files to internal storage: http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
So I currently have the image being selected and it's path and have everything being POST-ed correctly I just now need to figure out how to send a file over as well, within the JSON if possible.
Here is my code
package com.sdsdo;
import java.io.File;
import java.io.IOException;
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.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class wardrobe extends Activity{
//set variable for the fields
private EditText nameField;
private Spinner typeField;
private EditText colorField;
private Spinner seasonField;
private EditText sizeField;
private EditText quantityField;
private ImageView imageField;
private ProgressBar progressBarField;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wardrobe);
ImageView user_photo = (ImageView) findViewById(R.id.user_photo);
//button for upload image
Button uploadImageButton = (Button) findViewById(R.id.uploadImageButton);
//button for posting details
Button postWardrobe = (Button) findViewById(R.id.postButton);
//Value of fields
nameField = (EditText) findViewById(R.id.nameFieldWardrobeScreen);
typeField = (Spinner) findViewById(R.id.typeFieldWardrobeScreen);
colorField = (EditText) findViewById(R.id.colorFieldWardrobeScreen);
seasonField = (Spinner) findViewById(R.id.seasonFieldWardrobeScreen);
sizeField = (EditText) findViewById(R.id.sizeFieldWardrobeScreen);
quantityField = (EditText) findViewById(R.id.quantityFieldWardrobeScreen);
imageField = (ImageView) findViewById(R.id.user_photo);
progressBarField = (ProgressBar) findViewById(R.id.progressBarWardrobe);
progressBarField.setVisibility(View.GONE);
//Creating spinner for select/options for type field
Spinner spinnerType = (Spinner) findViewById(R.id.typeFieldWardrobeScreen);
ArrayAdapter<CharSequence> adapterTypeArray = ArrayAdapter.createFromResource(this, R.array.type_array, android.R.layout.simple_spinner_item);
adapterTypeArray.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerType.setAdapter(adapterTypeArray);
//Creating spinner for select/options for season field
Spinner spinnerSeason = (Spinner) findViewById(R.id.seasonFieldWardrobeScreen);
ArrayAdapter<CharSequence> adapterSeasonArray = ArrayAdapter.createFromResource(this, R.array.season_array, android.R.layout.simple_spinner_item);
adapterSeasonArray.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSeason.setAdapter(adapterSeasonArray);
uploadImageButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//below allows you to open the phones gallery
Image_Picker_Dialog();
}
});
postWardrobe.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//validate input and that something was entered
if(nameField.getText().toString().length()<1 || colorField.getText().toString().length()<1 || sizeField.getText().toString().length()<1 || quantityField.getText().toString().length()<1) {
//missing required info (null was this but lets see)
Toast.makeText(getApplicationContext(), "Please complete all sections!", Toast.LENGTH_LONG).show();
} else {
JSONObject dataWardrobe = new JSONObject();
try {
dataWardrobe.put("type", typeField.getSelectedItem().toString());
dataWardrobe.put("color", colorField.getText().toString());
dataWardrobe.put("season", seasonField.getSelectedItem().toString());
dataWardrobe.put("size", sizeField.getText().toString());
dataWardrobe.put("quantity", quantityField.getText().toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//make progress bar visible
progressBarField.setVisibility(View.VISIBLE);
//execute the post request
new dataSend().execute(dataWardrobe);
}
//below should send data over
}
});
}
// After the selection of image you will retun on the main activity with bitmap image
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Utility.GALLERY_PICTURE)
{
// data contains result
// Do some task
Image_Selecting_Task(data);
} else if (requestCode == Utility.CAMERA_PICTURE)
{
// Do some task
Image_Selecting_Task(data);
}
}
public void Image_Picker_Dialog()
{
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);
myAlertDialog.setTitle("Pictures Option");
myAlertDialog.setMessage("Select Picture Mode");
myAlertDialog.setPositiveButton("Gallery", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
Utility.pictureActionIntent = new Intent(Intent.ACTION_GET_CONTENT, null);
Utility.pictureActionIntent.setType("image/*");
Utility.pictureActionIntent.putExtra("return-data", true);
startActivityForResult(Utility.pictureActionIntent, Utility.GALLERY_PICTURE);
}
});
myAlertDialog.setNegativeButton("Camera", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
Utility.pictureActionIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(Utility.pictureActionIntent, Utility.CAMERA_PICTURE);
}
});
myAlertDialog.show();
}
public void Image_Selecting_Task(Intent data)
{
ImageView user_photo = (ImageView) findViewById(R.id.user_photo);
try
{
Utility.uri = data.getData();
if (Utility.uri != null)
{
// User had pick an image.
Cursor cursor = getContentResolver().query(Utility.uri, new String[]
{ android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
cursor.moveToFirst();
// Link to the image
final String imageFilePath = cursor.getString(0);
//Assign string path to File
Utility.Default_DIR = new File(imageFilePath);
// Create new dir MY_IMAGES_DIR if not created and copy image into that dir and store that image path in valid_photo
Utility.Create_MY_IMAGES_DIR();
// Copy your image
Utility.copyFile(Utility.Default_DIR, Utility.MY_IMG_DIR);
// Get new image path and decode it
Bitmap b = Utility.decodeFile(Utility.Paste_Target_Location);
// use new copied path and use anywhere
String valid_photo = Utility.Paste_Target_Location.toString();
b = Bitmap.createScaledBitmap(b, 150, 150, true);
//set your selected image in image view
user_photo.setImageBitmap(b);
cursor.close();
} else
{
Toast toast = Toast.makeText(this, "Sorry!!! You haven't selecet any image.", Toast.LENGTH_LONG);
toast.show();
}
} catch (Exception e)
{
// you get this when you will not select any single image
Log.e("onActivityResult", "" + e);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
//Calling code for different selected menu options
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
//show settings activity screen (main preference activity file)
case R.id.wardrobe:
Intent intent = new Intent(wardrobe.this, wardrobe.class);
startActivity(intent);
//if index button clicked in menu sub-menu options
case R.id.matches:
Toast.makeText(this, "matches was clicked!", 5).show();
//if index button clicked in menu sub-menu options
case R.id.worn:
Toast.makeText(this, "worn was clicked!", 5).show();
default:
}
return super.onOptionsItemSelected(item);
}
private class dataSend extends AsyncTask<JSONObject, Integer, Double> {
protected Double doInBackground(JSONObject... params) {
// TODO Auto-generated method stub
postData(params[0]);
return null;
}
protected void onPostExecute(Double result) {
progressBarField.setVisibility(View.GONE);
Toast.makeText(wardrobe.this, "info sent", Toast.LENGTH_LONG).show();
}
protected void onProgressUpdate(Integer... progress) {
progressBarField.setProgress(progress[0]);
}
public void postData(JSONObject dataWardrobe) {
Log.v("posting data", "poooooost");
// Create a new HttpClient and Post Header
//int TIMEOUT_MILLISEC = 10000; // = 10 seconds
HttpParams httpParams = new BasicHttpParams();
//HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
//HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient httpclient = new DefaultHttpClient(httpParams);
HttpPost httppost = new HttpPost("http://10.0.2.2:3000/wardrobe");
Log.v("posteed", "posteed url");
try {
Log.v("trying data", "prep");
//add data
StringEntity se = new StringEntity( dataWardrobe.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
Log.v("posteed", "posteed 11");
// execute http post request
HttpResponse response = httpclient.execute(httppost);
Log.v("posteed", "posteed 22");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
Log.e("sds", e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("sds 22", e.getMessage());
}
}
}
}
Here is similar responses I found but I am not sure how to implement it correctly...
Send Base64 image from Android with JSON to php webservice, decode, save to SQL
How to convert image into byte array and byte array to base64 String in android?
you should send it as a Multipart Entity. this way you can send image and other string parameters together.
For this you will need the following files
apache-mime4j-0.6.jar
httpmime-4.0.1.jar
check the following link for details.
http://www.coderzheaven.com/2011/08/16/how-to-upload-multiple-files-in-one-request-along-with-other-string-parameters-in-android/