Im a little lost on this. Trying to pass variables onto another class for output. This class gets the variable.
OneWeekPlan_Start_Btn.java
package com.th3ramr0d.prtmanager;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class OneWeekPlan_Start_Btn extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.oneweek_day1);
EditText inputTxt = (EditText) findViewById(R.id.wkOneDayOneInstructorName);
String wk1day1_inst = inputTxt.getText().toString();
Button oneweekDay2 = (Button) findViewById(R.id.wk1Day2);
oneweekDay2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("com.th3ramr0d.prtmanager.ONEWEEKDAYTWO"));
}
});
}
}
I want to be able to use the variable wk1day1_inst in the following class
Save_File.java
package com.th3ramr0d.prtmanager;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.view.View.OnClickListener;
public class Save_File extends Activity implements OnClickListener{
Button writeExcelButton;
static String TAG = "ExelLog";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.save_file);
writeExcelButton = (Button) findViewById(R.id.wk1Save);
writeExcelButton.setOnClickListener(this);
}
public void onClick(View v)
{
EditText inputTxt = (EditText) findViewById(R.id.wkOneSaveFile);
String fileName = inputTxt.getText().toString();
switch (v.getId())
{
case R.id.wk1Save:
saveExcelFile(this,fileName + ".xls");
}
setContentView(R.layout.created);
}
private static boolean saveExcelFile(Context context, String fileName) {
// check if available and not read only
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
Log.e(TAG, "Storage not available or read only");
return false;
}
boolean success = false;
//New Workbook
Workbook wb = new HSSFWorkbook();
Cell c1 = null;
//Cell style for header row
CellStyle cs = wb.createCellStyle();
cs.setFillForegroundColor(HSSFColor.LIME.index);
cs.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
//New Sheet
Sheet sheet1 = null;
sheet1 = wb.createSheet("My PT Plan");
// Generate column headings
Row row = sheet1.createRow(0);
c1 = row.createCell(0);
c1.setCellValue("FUCK YOU SCIENCE!");
c1.setCellStyle(cs);
c1 = row.createCell(1);
c1.setCellValue("Quantity");
c1.setCellStyle(cs);
c1 = row.createCell(2);
c1.setCellValue("Price");
c1.setCellStyle(cs);
sheet1.setColumnWidth(0, (15 * 500));
sheet1.setColumnWidth(1, (15 * 500));
sheet1.setColumnWidth(2, (15 * 500));
// Create a path where we will place our List of objects on external storage
File file = new File(context.getExternalFilesDir(null), fileName);
FileOutputStream os = null;
try {
os = new FileOutputStream(file);
wb.write(os);
Log.w("FileUtils", "Writing file" + file);
success = true;
} catch (IOException e) {
Log.w("FileUtils", "Error writing " + file, e);
} catch (Exception e) {
Log.w("FileUtils", "Failed to save file", e);
} finally {
try {
if (null != os)
os.close();
} catch (Exception ex) {
}
}
return success;
}
public static boolean isExternalStorageReadOnly() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
return true;
}
return false;
}
public static boolean isExternalStorageAvailable() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
return true;
}
return false;
}
}
More specifically I want to be able to use that variable for the spreadsheet. ie
c1 = row.createCell(0);
c1.setCellValue(wk1day1_inst);
c1.setCellStyle(cs);
Thanks for any help!
You can pass data between two activities using Intent.
Intent intent = new Intent (OneWeekPlan_Start_Btn.this, Save_File.class);
intent.putExtra("wk1day1_inst", wk1day1_ins);
startActivity(intent);
And in your next Activity, use this:
String wk1day1_inst = getIntent().getStringExtra("wk1day1_inst");
Hope this helps.
You can use SharedPreferences to save value of variable. It's advantage over putExtra of Intent is that with SharedPreferences the value of variable can be accessed inside any activity while Intent only allows to access variable in 1 activity.
//Save the value in OneWeekPlan_Start_Btn class
SharedPreferences.Editor editor = settings.edit();
editor.putString("weekday", wk1day1_inst);
editor.commit();
//Access the value in Save_File class
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
String wk1day = settings.getString("weekday", "");
Related
I'm trying to make an inventory apps to save item by item into internal storage. Here is my layout. The problem is it possible to save arraylist into document text file / other internal storage? Because fos.write(listitem.getBytes()); should be in Int. Here is my code from Activity2
package com.example.java;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
public class MainActivity2 extends AppCompatActivity {
public static final String extraint = "1";
public static final String namabarang = "2";
public static final String jumlahstock ="3";
public static final String FILE_NAME="example.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Intent intent = getIntent();
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.planets_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
public void onBtnClick(View view){
TextView plain1 = findViewById(R.id.NamaBarang);
TextView plain2 = findViewById(R.id.SKU);
TextView plain3 = findViewById(R.id.JumlahStok);
TextView plain4 = findViewById(R.id.HargaBeli);
TextView plain5 = findViewById(R.id.HargaJual);
Intent intent = new Intent(this,MainActivity3.class);
String x = "1";
String text = plain1.getText().toString();
FileOutputStream fos = null;
Item m1 = new Item("a","1");
Item m2 = new Item("b","2");
Item m3 = new Item("c","3");
ArrayList<Item> listitem = new ArrayList<>();
listitem.add(m1);
listitem.add(m2);
listitem.add(m3);
try {
fos = openFileOutput(FILE_NAME, MODE_PRIVATE);
fos.write(listitem.getBytes());
Toast.makeText(this,"Saved to" +getFilesDir() + "/" + FILE_NAME,Toast.LENGTH_LONG).show();
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
if(fos != null){
try{
fos.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
intent.putExtra(extraint,x);
intent.putExtra(FILE_NAME,text);
intent.putExtra(namabarang,plain1.getText().toString());
intent.putExtra(jumlahstock,plain3.getText().toString());
startActivity(intent);
}
}
Here is another code from Activity 3
package com.example.java;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.renderscript.ScriptGroup;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ListView;
import org.w3c.dom.Element;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Array;
import java.util.ArrayList;
import java.util.Arrays;
public class MainActivity3 extends AppCompatActivity {
private static final String Tag = "MainAcitivity3";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
Log.d(Tag, "onCreate: Started.");
ListView mListView = (ListView) findViewById(R.id.listView);
Intent intent = getIntent();
String[] barang = new String[20];
String[] jumlah = new String[20];
ArrayList<Item> itemlist = new ArrayList<Item>();
int loop=0;
barang[loop] = intent.getStringExtra(MainActivity2.namabarang);
jumlah[loop] = intent.getStringExtra(MainActivity2.jumlahstock);
loop++;
FileInputStream fis = null;
StringBuilder sb = new StringBuilder();
try {
fis = openFileInput(MainActivity2.FILE_NAME);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String text;
while ((text = br.readLine()) != null){
sb.append(text).append("\n");
}
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally {
if(fis!=null){
try{
fis.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
String result=sb.toString();
for(int i=0;i<loop;i++) {
Item sparepart = new Item(result, result);
itemlist.add(sparepart);
}
PersonListAdapter adapter = new PersonListAdapter(this, R.layout.adapter_view_layout,itemlist);
mListView.setAdapter(adapter);
String number = intent.getStringExtra(MainActivity2.extraint);
if(number != null) {
FrameLayout lay = (FrameLayout) findViewById(R.id.frames);
if (number.equals("1")) {
lay.setVisibility(View.INVISIBLE);
mListView.setVisibility(View.VISIBLE);
} else {
}
}
else{}
}
public void onBtnClick (View view){
Intent intent = new Intent(this,MainActivity2.class);
startActivity(intent);
}
}
The apps supposed to save one item by item into the internal storage which where i try to utilize array to save the into the internal storage, but it it possible to save and read array to internal storage?
My android app was supposed to send an image to a local java server via sockets and after processing the image the result has to be sent to the app again and i am supposed to display it in the text view.I have successfully received the result but while i am trying to display the result in the text view the app crashes showing the following error.
Error: java.lang.NullPointerException: Attempt to invoke virtual method 'void java.text.BreakIterator.setText(java.lang.String)' on a null object reference
I am new to Android programming.I have tried many things but couldnt solve it.Please help me!
Thanks in advance!
Code: Main Activity
package com.example.image1;
import android.app.Activity;
import android.app.MediaRouteButton;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.Nullable;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.BreakIterator;
import java.util.Objects;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
private static final int SELECT_PICTURE = 1;
private static final int GET_PICTURE =1 ;
private PrintWriter printwriter;
public static String selectedImagePath;
public static String selectedImageUri;
private ImageView img;
public static String st;
TextView status1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.println("34");
img = (ImageView) findViewById(R.id.ivPic);
System.out.println("36");
Button send = (Button) findViewById(R.id.bSend);
//status = (TextView) findViewById(R.id.tvStatus);
status1 = (TextView) findViewById(R.id.result);
((Button) findViewById(R.id.bBrowse))
.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
System.out.println("40");
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"),
SELECT_PICTURE);
System.out.println("47");
}
});
;
System.out.println("51");
//status1.setText("fjfjf");
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//status1.setText("fjfjf");
new SendImageTask().execute();
//final TextView status1 = (TextView) findViewById(R.id.result);
//status1.setText(s);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
TextView path = (TextView) findViewById(R.id.tvPath);
path.setText("Image Path : " + selectedImagePath);
img.setImageURI(selectedImageUri);
}
}
}
public String getPath(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(projection[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
return filePath;
}
}
SendImageTask code
package com.example.image1;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Base64;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.BreakIterator;
class SendImageTask extends AsyncTask<Void, Void, String> {
private PrintWriter printwriter;
private Bitmap IOUtils;
private BreakIterator status1;
private static String st;
#SuppressLint("WrongThread")
#Override
protected String doInBackground(Void... voids) {
Socket sock;
try {
sock = new Socket("192.168.43.120", 8000);
System.out.println("Connecting...");
System.out.println("Sending...");
String s = getFileToByte(MainActivity.selectedImagePath);
System.out.println(s);
printwriter = new PrintWriter(sock.getOutputStream(), true);
printwriter.write(String.valueOf(s)); // write the message to output stream
printwriter.flush();
printwriter.close();
sock.close();
try {
System.out.println("Another socket");
Socket sock1 = new Socket("192.168.43.120", 6000);
System.out.println("Connecting1...");
InputStreamReader streamReader = new InputStreamReader(sock1.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
st = reader.readLine();
System.out.println(st);
System.out.println("ascscasc");
sock1.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return st;
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return st;
}
protected void onPostExecute(String st){
System.out.println("asasdcwdcwdc");
System.out.println(st);
status1.setText(String.valueOf(st));
}
public static String getFileToByte(String filePath){
Bitmap bmp = null;
ByteArrayOutputStream bos = null;
byte[] bt = null;
String encodeString = null;
try{
bmp = BitmapFactory.decodeFile(filePath);
bos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, bos);
bt = bos.toByteArray();
encodeString = Base64.encodeToString(bt, Base64.DEFAULT);
}
catch (Exception e){
e.printStackTrace();
}
String str1=encodeString.replaceAll("[\r\n]+", " ");
str1 = str1.replaceAll("\\s+","");
return "data:image/jpeg;base64,"+str1+"/n";
}
}
First my app was crashing because i was doing the textView operation in the doInBackground method and then after only i learnt that ui operations cant be done there. So then i executed those commands in onPostExecute method.But still my app is crashing saying NullPointerException.I will also include the logcat here.Thanks in advance.
Logcat:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.image1, PID: 20241
java.lang.NullPointerException: Attempt to invoke virtual method 'void java.text.BreakIterator.setText(java.lang.String)' on a null object reference
at com.example.image1.SendImageTask.onPostExecute(SendImageTask.java:147)
at com.example.image1.SendImageTask.onPostExecute(SendImageTask.java:19)
at android.os.AsyncTask.finish(AsyncTask.java:667)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:684)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:186)
at android.app.ActivityThread.main(ActivityThread.java:6509)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:914)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:804)
I/Process: Sending signal. PID: 20241 SIG: 9
You need to initialize your BreakIterator object status1 otherwise it would be null.
I've not used BreakIterator, but a quick look at the docs shows that this is how you get an instance.
BreakIterator status1 = BreakIterator.getWordInstance();
Bottom line is to initialize it before using it.
i'm new to android and i have a problem. i want to sent variable "adresa" from for (or while) loop to another activity when click on button, but allways send last value from loop.
here is code:
PS. sorry for my english
this is first activity
package com.example.locationtracker;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.app.ActionBar.LayoutParams;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.widget.Button;
public class DatabasesActivity extends Activity {
public static String adresa;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final DBAdapter2 db = new DBAdapter2(this);
//---get a posao---
db.open();
final Cursor c = db.getPosao(0);
if (c.moveToFirst()){
final int x = 0;
final LinearLayout lm = (LinearLayout) findViewById(R.id.linearMain);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// while (c.moveToNext()) {
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
final Button button = new Button(this) ;
button.setId(x+1);
button.setText("id: " + c.getString(0) + "\n" +
"Ime: " + c.getString(1) + "\n" +
"Adresa: " + c.getString(2) + "\n" +
"Telefon: " + c.getString(3) + "\n" +
"Napomena: " + c.getString(4) + "\n" +
"Status: " + c.getString(5));
button.setLayoutParams(params);
adresa = c.getString(2);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Perform action on click
Intent activityChangeIntent = new Intent(DatabasesActivity.this, PrikazMape.class);
activityChangeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activityChangeIntent.putExtra("add", adresa);
DatabasesActivity.this.startActivity(activityChangeIntent);
}
});
//Add button to LinearLayout
ll.addView(button);
//Add button to LinearLayout defined in XML
lm.addView(ll);
}
}
else
Toast.makeText(this, "No contact found", Toast.LENGTH_LONG).show();
db.close();
try {
String destPath = "/data/data/" + getPackageName() +
"/databases";
File f = new File(destPath);
if (!f.exists()) {
f.mkdirs();
f.createNewFile();
//---copy the db from the assets folder into
// the databases folder---
CopyDB(getBaseContext().getAssets().open("mydb"),
new FileOutputStream(destPath + "/MyDB"));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void CopyDB(InputStream inputStream,
OutputStream outputStream) throws IOException {
//---copy 1K bytes at a time---
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
}
and second
package com.example.locationtracker;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import com.google.android.gms.maps.*;
import com.google.android.gms.maps.model.*;
import android.app.Activity;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
public class PrikazMape extends Activity {
double latitude;
double longtitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_activity);
Intent mInt = getIntent();
String adresa = mInt.getStringExtra("add");
Geocoder geoCoder = new Geocoder(PrikazMape.this);
try {
List<Address> addresses =
geoCoder.getFromLocationName(adresa, 1);
if (addresses.size() > 0) {
latitude = addresses.get(0).getLatitude();
longtitude = addresses.get(0).getLongitude(); }
} catch (IOException e) { // TODO Auto-generated catch block
e.printStackTrace(); }
LatLng pos = new LatLng(latitude, longtitude);
// Get a handle to the Map Fragment
GoogleMap map = ((MapFragment) getFragmentManager()
.findFragmentById(R.id.map)).getMap();
map.setMyLocationEnabled(true);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(pos, 13));
map.addMarker(new MarkerOptions()
.title(adresa)
.snippet("Ovde nešto napiši.")
.position(pos));
}
}
thanks!
The problem is that you are setting up multiple buttons, but you only have one adresa for the whole object. When you say
adresa = c.getString(2);
you will overwrite the value that was previously in adresa. The problem, though, is that setting up the listener:
public void onClick(View v) {
// Perform action on click
Intent activityChangeIntent = new Intent(DatabasesActivity.this, PrikazMape.class);
activityChangeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activityChangeIntent.putExtra("add", adresa);
DatabasesActivity.this.startActivity(activityChangeIntent);
}
does not copy the current value of adresa into the listener when you set it up. It just says that when the button is clicked, to run the code in onClick; and that code will use whatever string adresa currently has, which will be whatever it was last set to in the loop.
One way to solve this is to define your own class that implements OnClickListener, instead of relying on an anonymous class. Then you can add a constructor that lets you store the address in the listener.
private class OnClickListenerWithAdresa {
private String mAdresa;
public OnClickListenerWithAdresa(String adresa) {
this.mAdresa = adresa;
}
public void onClick(View v) {
// Perform action on click
Intent activityChangeIntent = new Intent(DatabasesActivity.this, PrikazMape.class);
activityChangeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activityChangeIntent.putExtra("add", mAdresa); // NOTE use the listener's private field
DatabasesActivity.this.startActivity(activityChangeIntent);
}
}
and then, inside your loop, to set the listener:
button.setOnClickListener(new OnClickListenerWithAdresa(adresa));
This will take the current value of adresa and copy the String reference to the new OnClickListenerWithAdresa. This will ensure that the correct adresa is used for each button.
Another way, that I think is less clean, is to define a final variable inside the loop, before setting up the listener:
final String adresaForListener = adresa;
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Perform action on click
Intent activityChangeIntent = new Intent(DatabasesActivity.this, PrikazMape.class);
activityChangeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activityChangeIntent.putExtra("add", adresaForListener);
DatabasesActivity.this.startActivity(activityChangeIntent);
}
});
This works because you're declaring the new final variable inside the loop, and then using it inside the anonymous class; the end result will be that a new adresaForListener variable will be created each time you create a new listener, so therefore each listener will have its own. It's called a "closure".
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/
Getting this exception while executing on emulator.
I think this is related to some memory issue.
Because its working fine when am trying it on my phone.
Anyone help me to find the real reason for this problem?
Galleryview.java
package example.hitwallhd;
import example.hitwallhd.ImageDownloader;
import example.hitwallhd.ImageDownloader.ImageLoaderListener;
import example.hitwallhd.R;
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.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ImageView.ScaleType;
public class Galleryview extends Activity {
private ProgressBar pb;
private Button save,bnxt,bprv;
private ImageView img;
private static Bitmap bmp;
private TextView percent;
private FileOutputStream fos;
private ImageDownloader mDownloader;
TextView t1,t2;
String num,cate,addrs,urladdrs,pviews,pdown,sele;
int savecount=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_galleryview);
save.setEnabled(false);
initViews();
Bundle extras = getIntent().getExtras();
num = extras.getString("num");
cate = extras.getString("category");
sele = extras.getString("sele");
addrs= extras.getString("picno");
t1 =(TextView) findViewById(R.id.textView2);
t2 =(TextView) findViewById(R.id.textView3);
//t1.setText(pviews);
//t2.setText(pdown);
urladdrs="http://someaddrs.com/wallpapers/"+cate+"/"+addrs;
/*--- instantiate our downloader passing it required components ---*/
mDownloader = new ImageDownloader(urladdrs, pb, save, img, percent, Galleryview.this, bmp, new ImageLoaderListener() {
#Override
public void onImageDownloaded(Bitmap bmp) {
Galleryview.bmp = bmp;
/*--- here we assign the value of bmp field in our Loader class
* to the bmp field of the current class ---*/
}
});
/*--- we need to call execute() since nothing will happen otherwise ---*/
mDownloader.execute();
save.setEnabled(true);
}
private void initViews() {
save = (Button) findViewById(R.id.save);
//bnxt=(Button) findViewById(R.id.bnext);
//bprv=(Button) findViewById(R.id.bprev);
/*--- we are using 'this' because our class implements the OnClickListener ---*/
img = (ImageView) findViewById(R.id.imageView1);
img.setScaleType(ScaleType.CENTER_CROP);
pb = (ProgressBar) findViewById(R.id.pbDownload);
pb.setVisibility(View.INVISIBLE);
percent = (TextView) findViewById(R.id.textView1);
percent.setVisibility(View.INVISIBLE);
}
public void onclick_next(View v)
{
bprv.setEnabled(true);
GetData obj = new GetData();
int nxt=Integer.parseInt(num)+1;
num=String.valueOf(nxt);
String urls="http://someaddrs.com/wallpapers/newlist.php?cate="+cate+"&no="+num+"&prev=0";
obj.execute(urls);
}
public void onclick_prev(View v)
{
bnxt.setEnabled(true);
GetData obj = new GetData();
int nxt=Integer.parseInt(num)-1;
num=String.valueOf(nxt);
String urls="http://someaddrs.com/wallpapers/newlist.php?cate="+cate+"&no="+num+"&prev=1";
obj.execute(urls);
}
public void onclick_save(View v)
{
saveImageToSD();
String cnum;
if(urladdrs.equals("nexterror"))
{
int nxt=Integer.parseInt(num)-1;
cnum=String.valueOf(nxt);
}
else if(urladdrs.equals("preverror"))
{
int nxt=Integer.parseInt(num)+1;
cnum=String.valueOf(nxt);
}
else
cnum=num;
savecount=1;
GetData obj = new GetData();
String urls="http://someaddrs.com/wallpapers/downloadcount.php?no="+cnum;
obj.execute(urls);
}
private void saveImageToSD() {
/*--- this method will save your downloaded image to SD card ---*/
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
/*--- you can select your preferred CompressFormat and quality.
* I'm going to use JPEG and 100% quality ---*/
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
/*--- create a new file on SD card ---*/
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + num+"Image.jpg");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
/*--- create a new FileOutputStream and write bytes to file ---*/
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fos.write(bytes.toByteArray());
fos.close();
Toast.makeText(this, "Image saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
Intent pview = new Intent(Galleryview.this,HitWall.class);
startActivity(pview);
}
public void looperfn()
{
t1 =(TextView) findViewById(R.id.textView2);
t2 =(TextView) findViewById(R.id.textView3);
t1.setText(pviews);
t2.setText(pdown);
if(urladdrs.equals("nexterror"))
{
int nxt=Integer.parseInt(num)-1;
num=String.valueOf(nxt);
bnxt.setEnabled(false);
}
else if(urladdrs.equals("preverror"))
{
int nxt=Integer.parseInt(num)+1;
num=String.valueOf(nxt);
bprv.setEnabled(false);
}
else
{
//t1.setText(urladdrs);
urladdrs="http://someaddrs.com/wallpapers/"+cate+"/"+urladdrs;
mDownloader = new ImageDownloader(urladdrs, pb, save, img, percent, Galleryview.this, bmp, new ImageLoaderListener() {
#Override
public void onImageDownloaded(Bitmap bmp) {
Galleryview.bmp = bmp;
/*--- here we assign the value of bmp field in our Loader class
* to the bmp field of the current class ---*/
}
});
/*--- we need to call execute() since nothing will happen otherwise ---*/
mDownloader.execute();
}
}
public class GetData extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
BufferedReader reader =null;
String data =null;
try{
HttpClient client = new DefaultHttpClient();
URI uri=new URI(params[0]);
HttpGet get =new HttpGet(uri);
HttpResponse response= client.execute(get);
InputStream stream=response.getEntity().getContent();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer =new StringBuffer("");
String line="";
while((line=reader.readLine())!=null){
buffer.append(line);
}
reader.close();
data = buffer.toString();
if(data.equals("preverror")||data.equals("nexterror"))
{
return data;
}
else
{
pviews=data.substring(data.indexOf("|")+1,data.indexOf(":"));
pviews=" Views : "+pviews;
pdown=data.substring(data.indexOf(":")+1, data.length());
pdown=" Downloads : "+pdown;
data=data.substring(0, data.indexOf("|"));
return data;
}
//data=data.substring(0, data.indexOf("|"));
//t1.setText(data);
}
catch(URISyntaxException e){
e.printStackTrace();
}
catch(ClientProtocolException f){
f.printStackTrace();
}
catch(IOException g){
g.printStackTrace();
}
finally{
if(reader!=null){
try{
reader.close();
}
catch(Exception e){
}
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
urladdrs=result;
if(savecount==0)
{
looperfn();
}
else
savecount=0;
}
}
}
This type of issue is arrived due to memory leakage.
the main problem is that there is Java.lang.NullPointerException and this type of exception arrives when there is low virtual memory.
As there is low virtual memory in emulator so it is getting the error and the phone has the sufficient virtual memory to display and load the image in the memory.
You have an exception in Galleryview.java at line 57. Please provide the peace of code around line 57 or the whole Galleryview.java.