Android Java Error OutOfMemory - java

currently I am developing an Android Application (Native). In my application, I need to load many images and that cause a problem.
The problem is:
1. When I first open the app after deploy it on my android phone, it works fine. However, after I close the application (by clicking the back button), and then I open the application again, the app closed unexpectedly. When I check the logcat, I found out that it was closed because of OutOfMemory error.
2. Second problem: after I open my application, and I go to the next page, it also give me OutOfMemory error.
I guess, the problem occur because I load too many images. After I do some searching on the internet, it suggest me to do System.gc
But unfortunately, it did not work for me.
Here is my code:
Homepage_Activity.java
package dev.com.friseur;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import dev.friseur.insert.AddComment;
import dev.friseur.rest.Photo;
import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
public class HomePage extends ActionBarActivity {
private String p_id = "1";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
Intent intent = getIntent();
int size = Integer.parseInt(intent.getStringExtra("size")) * 2;
LinearLayout hp = (LinearLayout)findViewById(R.id.homepage);
Photo photo = new Photo(hp, this, size);
photo.execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home_page, 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);
}
}
The photo.execute() code will call an asynchronous task. Here it is:
package dev.friseur.rest;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
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 dev.com.friseur.RecognizeFace;
import dev.com.friseur.ViewPhoto;
import dev.friseur.insert.AddComment;
import dev.friseur.insert.AddLike;
import android.R;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.SystemClock;
import android.text.InputFilter;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class Photo extends AsyncTask<String, Void, String>{
private Context context;
private LinearLayout homepage;
private int size;
private String sessionUname;
private String sessionUserid;
private File file;
private ArrayList<String> photo_id;
private ArrayList<String> imageName;
private ArrayList<String> date_upload;
private ArrayList<String> url_original;
private ArrayList<String> url_with_hair;
private ArrayList<String> caption;
private ArrayList<String> user_id;
private ArrayList<String> username;
private ArrayList<JSONArray> comments;
private ArrayList<Integer> totalcomment;
public Photo(LinearLayout homepage, Context context, int size){
this.context = context;
this.homepage = homepage;
this.size = size;
this.sessionUname = "testuser";
this.sessionUserid = "1";
photo_id = new ArrayList<String>();
imageName = new ArrayList<String>();
date_upload = new ArrayList<String>();
url_original = new ArrayList<String>();
url_with_hair = new ArrayList<String>();
caption = new ArrayList<String>();
user_id = new ArrayList<String>();
username = new ArrayList<String>();
comments = new ArrayList<JSONArray>();
totalcomment = new ArrayList<Integer>();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
InputStream is = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.43.8:8080/FriseurRest/WebService/GetPhotos");
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());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
int i = 0;
while ((line = reader.readLine()) != null) {
JSONObject json_data = new JSONObject(line);
photo_id.add(json_data.getString("p_id"));
imageName.add(json_data.getString("imagename"));
date_upload.add(json_data.getString("date_upload"));
url_original.add(json_data.getString("url_original"));
url_with_hair.add(json_data.getString("url_with_hair"));
caption.add(json_data.getString("caption"));
user_id.add(Integer.toString(json_data.getInt("user_id")));
username.add(json_data.getString("username"));
comments.add(json_data.getJSONArray("photoComments"));
totalcomment.add(json_data.getInt("total_comment"));
i++;
}
is.close();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
return null;
}
protected void onDestroy() {
System.gc();
Runtime.getRuntime().gc();
}
protected void onPostExecute(String p_id) {
for(int i = 0; i < imageName.size(); i++){
final int j = i;
LinearLayout photo = new LinearLayout(context);
photo.setOrientation(LinearLayout.VERTICAL);
photo.setPadding(0, 0, 0, 50);
LinearLayout postdesc = createPostDesc(i);
file = new File(Environment.getExternalStorageDirectory() + "/" + url_original.get(i), imageName.get(i));
Uri imgUri = Uri.fromFile(file);
ImageView img = new ImageView(context);
img.setImageURI(imgUri);
img.setMaxWidth(size);
img.setMinimumWidth(size);
img.setMaxHeight(size);
img.setMinimumHeight(size);
TextView tv = new TextView(context);
tv.setText(caption.get(i));
final LinearLayout showcomment = new LinearLayout(context);
showcomment.setOrientation(LinearLayout.VERTICAL);
showcomment.setPadding(0, 10, 0, 10);
try {
if(totalcomment.get(i) > 5){
LinearLayout more = new LinearLayout(context);
more.setPadding(0, 0, 0, 5);
TextView viewmore = new TextView(context);
viewmore.setTextColor(Color.GRAY);
viewmore.setText("View More Comments");
viewmore.setClickable(true);
viewmore.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(context, ViewPhoto.class);
intent.putExtra("size", size);
intent.putExtra("p_id", photo_id.get(j));
intent.putExtra("imageName", imageName.get(j));
intent.putExtra("date_upload", date_upload.get(j));
intent.putExtra("url_original", url_original.get(j));
intent.putExtra("url_with_hair", url_with_hair.get(j));
intent.putExtra("caption", caption.get(j));
intent.putExtra("user_id", user_id.get(j));
intent.putExtra("username", username.get(j));
context.startActivity(intent);
}
});
more.addView(viewmore);
showcomment.addView(more);
}
for(int k = 0; k < comments.get(i).length(); k++) {
//ArrayList<String> photoCom = comments.get(k);
//int userCom = photoCom.length();
JSONObject photoCom = comments.get(i).getJSONObject(k);
LinearLayout ll_comment = new LinearLayout(context);
ll_comment.setPadding(0, 0, 0, 5);
TextView uname = new TextView(context);
uname.setTextColor(Color.BLUE);
uname.setPadding(0,0,3,0);
uname.setText(photoCom.getString("com_username"));
TextView showcom = new TextView(context);
showcom.setText(photoCom.getString("com_desc"));
ll_comment.addView(uname);
ll_comment.addView(showcom);
showcomment.addView(ll_comment);
}
} catch (Exception e) {
}
LinearLayout addcomment = createAddComment(i);
final EditText et_comment = new EditText(context);
et_comment.setHint("Add Comment");
et_comment.setMaxWidth(size*3/4);
et_comment.setMinimumWidth(size*3/4);
int maxLength = 150;
et_comment.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength)});
Button button_comment = new Button(context);
button_comment.setText("Post");
button_comment.setTextSize(15);
button_comment.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String com = et_comment.getText().toString();
try{
AddComment ac = new AddComment(sessionUserid, com, photo_id.get(j));
ac.execute();
}
catch(Exception e){
CharSequence text = "Internet Connection Unstable. Please Try Again!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
LinearLayout ll_comment = new LinearLayout(context);
ll_comment.setPadding(0, 0, 0, 5);
TextView uname = new TextView(context);
uname.setTextColor(Color.BLUE);
uname.setPadding(0,0,3,0);
uname.setText(sessionUname);
TextView showcom = new TextView(context);
showcom.setText(com);
showcom.setAnimation(AnimationUtils.loadAnimation(context, android.R.anim.fade_in));
et_comment.setText("");
ll_comment.addView(uname);
ll_comment.addView(showcom);
showcomment.addView(ll_comment);
}
});
addcomment.addView(et_comment);
addcomment.addView(button_comment);
addcomment.setVisibility(View.GONE);
LinearLayout social = createSocialFeature(i, addcomment, et_comment);
photo.addView(postdesc);
photo.addView(img);
photo.addView(tv);
photo.addView(showcomment);
photo.addView(social);
photo.addView(addcomment);
homepage.addView(photo);
}
}
private LinearLayout createPostDesc(int i){
LinearLayout postdesc = new LinearLayout(context);
postdesc.setOrientation(LinearLayout.VERTICAL);
postdesc.setMinimumHeight(40);
TextView uname = new TextView(context);
uname.setText("#"+username.get(i));
TextView timeupload = new TextView(context);
timeupload.setText(date_upload.get(i));
if(i>0){
View separator = new View(context);
separator.setMinimumHeight(1);
separator.setBackgroundColor(Color.BLACK);
separator.setPadding(0, 10, 0, 0);
postdesc.addView(separator);
}
postdesc.addView(uname);
postdesc.addView(timeupload);
return postdesc;
}
private LinearLayout createSocialFeature(final int i, final LinearLayout addcomment, final EditText et_comment){
LinearLayout social = new LinearLayout(context);
social.setOrientation(LinearLayout.HORIZONTAL);
social.setMinimumHeight(40);
social.setPadding(0,10,10,0);
TextView tv_comment = new TextView(context);
tv_comment.setText("Add Comment");
tv_comment.setPadding(0, 0, 15, 0);
tv_comment.setClickable(true);
tv_comment.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addcomment.setVisibility(View.VISIBLE);
et_comment.setFocusableInTouchMode(true);
et_comment.setFocusable(true);
et_comment.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN , 0, 0, 0));
et_comment.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP , 0, 0, 0));
}
});
final TextView tv_like = new TextView(context);
tv_like.setText("Like");
tv_like.setClickable(true);
tv_like.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String like = tv_like.getText().toString();
try{
AddLike lk = new AddLike(sessionUserid, like, photo_id.get(i));
lk.execute();
}
catch(Exception e){
CharSequence text = "Internet Connection Unstable. Please Try Again!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
if(like.equals("Like")){
tv_like.setText("Unlike");
}
else{
tv_like.setText("Like");
}
}
});
social.addView(tv_comment);
social.addView(tv_like);
return social;
}
private LinearLayout createAddComment(int i){
LinearLayout addcomment = new LinearLayout(context);
addcomment.setId(Integer.parseInt(photo_id.get(i)));
addcomment.setOrientation(LinearLayout.HORIZONTAL);
addcomment.setPadding(0,20,0,0);
return addcomment;
}
}
This asynchronous task used to call the rest service.
What is wrong with my code? And how can I solve the OutOfMemory error. Any help would be appreciated. Thanks in advance

You can use lazyloading to fix this and follow this url for lazy loading:
https://github.com/nostra13/Android-Universal-Image-Loader

You can see my answer here.It will be useful to handle your bitmap efficiently.
How to make application more responsive which uses several bitmaps?

Related

how to save ArrayList into internal Storage

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?

Android Studio - Import data from csv and show in text (app crashes)

I am trying to import data from a csv file but my application crashes everytime. Below is my code that I have written. I receive no errors.
My main aim is to import data from the specified csv file and put in the variable called count_car. I want to show the value in the text box when I click the button. But I could not import the data from csv file.
package com.example.deneme2;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.String;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView text_zeros = findViewById(R.id.TextNumberZero);
TextView text_ones = findViewById(R.id.TextNumberOne);
TextView textView = findViewById(R.id.textView);
TextView textView1 = findViewById(R.id.textView2);
Button button = findViewById(R.id.button);
String path = "C:\\Users\\baran\\Desktop\\FALL 2020\\ELEC491\\deneme\\11111111111\\venv\\numberofcars.csv";
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
BufferedReader csvReader = null;
try {
csvReader = new BufferedReader(new FileReader(path));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String count_car = null;
int counting =0;
while (true) {
try {
if (!((count_car = csvReader.readLine()) != null)) break;
} catch (IOException e) {
e.printStackTrace();
}
//String[] data = count_car.split(",");
String count_cars = count_car;
int count_park= 100;
String countpark = String.valueOf(count_park);
String countcars = String.valueOf(count_cars);
text_ones.setText(countpark);
text_zeros.setText(countcars);
counting = counting +1 ;
if (counting == 50);
break;
}
}
});
}
}
EDIT 1
package com.example.exceldeneme;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.lang.String;
import java.util.List;
public class MainActivity<number_cars> extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView text_cars = findViewById(R.id.textCars);
readData();
String count_park = Arrays.toString(number_of_cars.get(1));
text_cars.setText(count_park);
}
private List<String[]> number_of_cars = new ArrayList<>();
private void readData() {
InputStream is = getResources().openRawResource(R.raw.numberofcars);
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, Charset.forName("UTF-8"))
);
String line = "";
try {
while(((line = reader.readLine()) != null)) {
String[] tokens = line.split(",");
number_of_cars.add(tokens);
Log.d("MyActivity","Just created"+ Arrays.toString(tokens));
}
}
catch (IOException e) {
Log.wtf("MyActivity","Error reading data file on line" + line, e);
e.printStackTrace();
}
}
}
I have changed the code. Now I am using different method. But the app starts to crash again. Is there any opinion? Thanks for answers.
EDIT 2
package com.example.exceldeneme;
import androidx.appcompat.app.AppCompatActivity;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.lang.String;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.List;
public class MainActivity<number_cars> extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
VideoView videoView = findViewById(R.id.video_view);
Button button = findViewById(R.id.button);
TextView text_cars = findViewById(R.id.textEmpty);
TextView text_total_lots = findViewById(R.id.textTotalLots);
readData();
int number_of_park = 100;
text_total_lots.setText(String.valueOf(number_of_park));
int counter = 0;
String videoPath = "android.resource://" + getPackageName() + "/" + R.raw.camera_out;
Uri uri = Uri.parse(videoPath);
videoView.setVideoURI(uri);
MediaController mediaController = new MediaController(this);
videoView.setMediaController(mediaController);
mediaController.setAnchorView(videoView);
//Log.d("Selam","This is my message"+ number_of_cars.get(0)[0]);
//String count_park = number_of_cars.get(0)[2];
//text_cars.setText(count_park);
for (String i : number_of_cars.get(0)){
counter = counter + 1 ;
}
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int counter = 0;
for (String i : number_of_cars.get(0)){
counter = counter + 1 ;
}
for (int i = 1; i < counter-1;i= i +1){
String count_park = number_of_cars.get(0)[i];
text_cars.setText(count_park);
//SystemClock.sleep(1000); //ms
Log.d("Selam","SORUN YOK");
}
}
});
}
private ArrayList<String[]> number_of_cars = new ArrayList<String[]>();
private void readData() {
InputStream is = getResources().openRawResource(R.raw.numberofcars);
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, Charset.forName("UTF-8"))
);
String line = "";
try {
while(((line = reader.readLine()) != null)) {
String[] tokens = line.split(",");
number_of_cars.add(tokens);
Log.d("MyActivity","Just created"+ Arrays.toString(tokens));
}
}
catch (IOException e) {
Log.wtf("MyActivity","Error reading data file on line" + line, e);
e.printStackTrace();
}
}
}
My final code is here. I have solved my problems and imported data from csv file. I have used videoview to show video. Now I am trying to solve the delay problem.
I want the below for loop function to wait for 1 second or 50 ms. But I could not find the solution.
for (int i = 1; i < counter-1;i= i +1){
String count_park = number_of_cars.get(0)[i];
text_cars.setText(count_park);
//SystemClock.sleep(1000); //ms
Log.d("Selam","SORUN YOK");
}
If anyone can help, I appreciate it :) Thanks for your answers.

JSON file parsing ran into errors in ANDROID

I am trying to parse data from json using an API, but I don't know for what reasons when I am calculating the size of m_name3 it is showing 0 but the data is being parsed through the file. When putting toast at String name = o.getString("name"); it is showing the content of name string, so this means it is parsing the data but not storing in arraylist. I don't know why. Please help!
package com.example.amitc.pvrathome;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
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.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import okhttp3.OkHttpClient;
public class msms extends AppCompatActivity {
String img_src;
private ArrayList<String> m_name3 = new ArrayList<>();
private ArrayList<String> m_release_year3 = new ArrayList<>();
private ArrayList<String> m_genre3 = new ArrayList<>();
private ArrayList<String> m_director3 = new ArrayList<>();
private ArrayList<String> m_rating3 = new ArrayList<>();
private ArrayList<String> m_actor3 = new ArrayList<>();
private ArrayList<String> m_desc3 = new ArrayList<>();
private ArrayList<String> m_imgsrc3 = new ArrayList<>();
StringRequest stringRequest;
Context mContext;
String url_all = "https://www.dropbox.com/s/ofzv2j16vq9ofmq/100MovieList.json?dl=1";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.msms);
new getIncomingIntent().execute();
ImageView imageView = findViewById(R.id.msms_image);
mContext = this;
Glide.with(this)
.load(img_src)
.apply(new RequestOptions()
.placeholder(R.drawable.rec)
.dontAnimate()
.error(R.drawable.movies))
.into(imageView);
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
//txt.setText("Searching by: "+ query);
} else if (Intent.ACTION_VIEW.equals(intent.getAction())) {
String uri = intent.getDataString();
final int index = Integer.parseInt(uri.replaceAll("[^0-9]", ""));
//
stringRequest = new StringRequest(Request.Method.GET,
url_all,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("movies");
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
String name = o.getString("name");
String year = o.getString("year");
String genre = o.getString("genre");
String rating = o.getString("rating");
String director = o.getString("directors_name");
String actor = o.getString("cast");
String img_src = o.getString("poster_src");
String desc = o.getString("description");
m_name3.add(name);
m_release_year3.add(year);
m_genre3.add(genre);
m_rating3.add(rating);
m_director3.add(director);
m_actor3.add(actor);
m_imgsrc3.add(img_src);
m_desc3.add(desc);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Some error Occured", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(msms.this);
requestQueue.add(stringRequest);
Toast.makeText(this, "Index: "+ m_name3.size(), Toast.LENGTH_SHORT).show();
// TextView m_name = findViewById(R.id.msms_name);
// m_name.setText(m_name3.get(index));
//
// TextView m_name1 = findViewById(R.id.msms_name1);
// m_name1.setText(m_name3.get(index));
// // TextView m_year = (TextView) findViewById(R.id.msms_year);
// // m_year.setText(year);
//
// TextView m_genre = findViewById(R.id.msms_genre);
// m_genre.setText(m_genre3.get(index));
//
// TextView m_rating = findViewById(R.id.msms_rating);
// m_rating.setText(m_rating3.get(index));
//
// TextView m_desc = findViewById(R.id.msms_desc);
// m_desc.setText(m_desc3.get(index));
//
// TextView m_direc = findViewById(R.id.msms_direc);
// m_direc.setText(m_director3.get(index));
//
// TextView m_actor = findViewById(R.id.msms_actor);
// m_actor.setText(m_actor3.get(index));
// Glide.with(this)
// .load(img_src)
// .apply(new RequestOptions()
// .placeholder(R.drawable.rec)
// .dontAnimate()
// .error(R.drawable.movies))
// .into(imageView);
}
}
public class getIncomingIntent extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
String name = getIntent().getStringExtra("names");
// String year = getIntent().getStringExtra("years");
String genre = getIntent().getStringExtra("genres");
String rating = getIntent().getStringExtra("ratings");
String desc = getIntent().getStringExtra("decss");
String director = getIntent().getStringExtra("direcs");
String actor = getIntent().getStringExtra("stars");
img_src = getIntent().getStringExtra("img1");
TextView m_name = (TextView) findViewById(R.id.msms_name);
m_name.setText(name);
TextView m_name1 = (TextView) findViewById(R.id.msms_name1);
m_name1.setText(name);
// TextView m_year = (TextView) findViewById(R.id.msms_year);
// m_year.setText(year);
TextView m_genre = (TextView) findViewById(R.id.msms_genre);
m_genre.setText(genre);
TextView m_rating = (TextView) findViewById(R.id.msms_rating);
m_rating.setText(rating);
TextView m_desc = (TextView) findViewById(R.id.msms_desc);
m_desc.setText(desc);
TextView m_direc = (TextView) findViewById(R.id.msms_direc);
m_direc.setText(director);
TextView m_actor = (TextView) findViewById(R.id.msms_actor);
m_actor.setText(actor);
return null;
}
}
}
EDITED:
package com.example.amitc.pvrathome;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
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.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import okhttp3.OkHttpClient;
public class msms extends AppCompatActivity {
String img_src;
private ArrayList<String> m_name3 = new ArrayList<>();
private ArrayList<String> m_release_year3 = new ArrayList<>();
private ArrayList<String> m_genre3 = new ArrayList<>();
private ArrayList<String> m_director3 = new ArrayList<>();
private ArrayList<String> m_rating3 = new ArrayList<>();
private ArrayList<String> m_actor3 = new ArrayList<>();
private ArrayList<String> m_desc3 = new ArrayList<>();
private ArrayList<String> m_imgsrc3 = new ArrayList<>();
StringRequest stringRequest;
Context mContext;
String url_all = "https://www.dropbox.com/s/ofzv2j16vq9ofmq/100MovieList.json?dl=1";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.msms);
new getIncomingIntent().execute();
ImageView imageView = findViewById(R.id.msms_image);
mContext = this;
Glide.with(this)
.load(img_src)
.apply(new RequestOptions()
.placeholder(R.drawable.rec)
.dontAnimate()
.error(R.drawable.movies))
.into(imageView);
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
//txt.setText("Searching by: "+ query);
} else if (Intent.ACTION_VIEW.equals(intent.getAction())) {
String uri = intent.getDataString();
final int index = Integer.parseInt(uri.replaceAll("[^0-9]", ""));
//
stringRequest = new StringRequest(Request.Method.GET,
url_all,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("movies");
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
String name = o.getString("name");
String year = o.getString("year");
String genre = o.getString("genre");
String rating = o.getString("rating");
String director = o.getString("directors_name");
String actor = o.getString("cast");
String img_src = o.getString("poster_src");
String desc = o.getString("description");
m_name3.add(name);
m_release_year3.add(year);
m_genre3.add(genre);
m_rating3.add(rating);
m_director3.add(director);
m_actor3.add(actor);
m_imgsrc3.add(img_src);
m_desc3.add(desc);
}
ProgressDialog progress;
progress= new ProgressDialog(mContext);
progress.setMessage("Loading...");
progress.show();
TextView m_name = findViewById(R.id.msms_name);
m_name.setText(m_name3.get(index));
TextView m_name1 = findViewById(R.id.msms_name1);
m_name1.setText(m_name3.get(index));
// TextView m_year = (TextView) findViewById(R.id.msms_year);
// m_year.setText(year);
TextView m_genre = findViewById(R.id.msms_genre);
m_genre.setText(m_genre3.get(index));
TextView m_rating = findViewById(R.id.msms_rating);
m_rating.setText(m_rating3.get(index));
TextView m_desc = findViewById(R.id.msms_desc);
m_desc.setText(m_desc3.get(index));
TextView m_direc = findViewById(R.id.msms_direc);
m_direc.setText(m_director3.get(index));
TextView m_actor = findViewById(R.id.msms_actor);
m_actor.setText(m_actor3.get(index));
ImageView imageView = findViewById(R.id.msms_image);
Glide.with(getApplicationContext())
.load(img_src)
.apply(new RequestOptions()
.placeholder(R.drawable.rec)
.dontAnimate()
.error(R.drawable.movies))
.into(imageView);
progress.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Some error Occured", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(msms.this);
requestQueue.add(stringRequest);
}
}
public class getIncomingIntent extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
String name = getIntent().getStringExtra("names");
// String year = getIntent().getStringExtra("years");
String genre = getIntent().getStringExtra("genres");
String rating = getIntent().getStringExtra("ratings");
String desc = getIntent().getStringExtra("decss");
String director = getIntent().getStringExtra("direcs");
String actor = getIntent().getStringExtra("stars");
img_src = getIntent().getStringExtra("img1");
TextView m_name = (TextView) findViewById(R.id.msms_name);
m_name.setText(name);
TextView m_name1 = (TextView) findViewById(R.id.msms_name1);
m_name1.setText(name);
// TextView m_year = (TextView) findViewById(R.id.msms_year);
// m_year.setText(year);
TextView m_genre = (TextView) findViewById(R.id.msms_genre);
m_genre.setText(genre);
TextView m_rating = (TextView) findViewById(R.id.msms_rating);
m_rating.setText(rating);
TextView m_desc = (TextView) findViewById(R.id.msms_desc);
m_desc.setText(desc);
TextView m_direc = (TextView) findViewById(R.id.msms_direc);
m_direc.setText(director);
TextView m_actor = (TextView) findViewById(R.id.msms_actor);
m_actor.setText(actor);
return null;
}
}
}
Since your stringRequest runs on a different thread, you can't be sure if you already have the response by the time you are showing the toast, so you should have a look at the size only after you have the response.
In short, move the toast inside of onResponse:
stringRequest = new StringRequest(Request.Method.GET,
url_all,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("movies");
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
String name = o.getString("name");
String year = o.getString("year");
String genre = o.getString("genre");
String rating = o.getString("rating");
String director = o.getString("directors_name");
String actor = o.getString("cast");
String img_src = o.getString("poster_src");
String desc = o.getString("description");
m_name3.add(name);
m_release_year3.add(year);
m_genre3.add(genre);
m_rating3.add(rating);
m_director3.add(director);
m_actor3.add(actor);
m_imgsrc3.add(img_src);
m_desc3.add(desc);
}
Toast.makeText(msms.this, "Index: "+ m_name3.size(), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Some error Occured", Toast.LENGTH_SHORT).show();
}
});

How to upload image Android to Server using PHP mysql

I have a problem about uploading images from android to a server, the problem is about the android version, my application can run on android version 2.3 but can not run on version > 2.3. these is my code
function TambahLokasi()
{
$base = $_REQUEST["gambar"];
if (isset($base)){
$suffix = createRandomID();
$image_name = "img_".$suffix."_".date("Y-m-d-H-m-s").".jpg";
$binary = base64_decode($base);
header("Content-Type: bitmap; charset=utf-8");
$file = fopen("gambar/" . $image_name, "wb");
fwrite($file, $binary);
fclose($file);
$username = $_POST['USERNAME'];
$loc_name = $_POST['LOCATION_NAME'];
$category = $_POST['CATEGORY'];
$address = $_POST['ADDRESS'];
$city = $_POST['CITY'];
$descript = $_POST['DESCRIPTION'];
$own = $_POST['OWNER'];
$lat = $_POST['lat'];
$lng = $_POST['lng'];
$query = "insert into location (USERNAME,LOCATION_NAME,CATEGORY,ADDRESS,CITY,DESCRIPTION,OWNER,lat,lng,gambar)values ('$username', '$loc_name', '$category', '$address','$city','$descript','$own','$lat','$lng','$image_name')";
//$query = "insert into pasien values ('','n', 'n', 'n', 'n','bar','','','n','n','n')";
$hasil = mysql_query($query);
if($hasil)
{
$respon["success"] = "1";
$respon["pesan"] = "Data berhasil diinput";
echo json_encode($respon);
}
else
{
$respon["success"] = "0";
$respon["pesan"] = "Data gagal diinput. Mohon cek kembali.";
echo json_encode($respon);
die($image_name);
}
}else {
die("No POST");
}
}
function createRandomID() {
$chars = "abcdefghijkmnopqrstuvwxyz0123456789?";
//srand((double) microtime() * 1000000);
$i = 0;
$pass = "";
while ($i <= 5) {
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
and this is java code
package com.adi.lib;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.adi.peta.AddLocation;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Base64;
import android.util.Log;
import android.widget.Button;
public class HttpUploader extends AsyncTask<String, Void, String>
{
String ba1;
Base64 base;
ProgressDialog pDialog;
Intent intent;
AddLocation add;
#SuppressWarnings("static-access")
protected String doInBackground(String... path)
{
String output = null;
for(String sdPath : path)
{
Bitmap bmp = BitmapFactory.decodeFile(sdPath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
double width = bmp.getWidth();
double height = bmp.getHeight();
double ratio = 400/width;
int newHeight = (int)(ratio*height);
bmp = Bitmap.createScaledBitmap(bmp, 400, newHeight, true);
bmp.compress(CompressFormat.JPEG, 90, bao);
byte[] ba= bao.toByteArray();
ba1 = base.encodeToString(ba, 0);
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("USERNAME", add.strUsername));
params.add(new BasicNameValuePair("LOCATION_NAME", add.strLocName));
params.add(new BasicNameValuePair("CATEGORY", add.strCategory));
params.add(new BasicNameValuePair("ADDRESS", add.strAddress));
params.add(new BasicNameValuePair("CITY", add.strCity));
params.add(new BasicNameValuePair("DESCRIPTION", add.strDesc));
params.add(new BasicNameValuePair("OWNER", add.strowner));
params.add(new BasicNameValuePair("lat", add.strlat));
params.add(new BasicNameValuePair("lng", add.strLng));
params.add(new BasicNameValuePair("gambar", ba1));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://batiktour.adi-hidayat.com/Android/AddLocation.php");
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
output = EntityUtils.toString(entity);
Log.i("GET RESPONSE--",output);
Log.e("log_tag ******", "good connection");
bmp.recycle();
}
catch (Exception e)
{
Log.e("log_tag ******",
"Error in http connection " + e.toString());
}
}
return output;
}
}
AddLocation.java
package com.adi.peta;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.logging.ErrorManager;
import android.widget.AdapterView.OnItemSelectedListener;
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.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.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.w3c.dom.Text;
import com.adi.lib.HttpUploader;
import com.adi.lib.JSONParser;
import com.adi.lib.SessionManager;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.R.string;
import android.location.Address;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.widget.AdapterView;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.support.v4.app.FragmentActivity;
import android.text.Html;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class AddLocation extends FragmentActivity implements LocationListener
{
Uri currImageURI;
GoogleMap googlemap;
ProgressDialog pDialog;
SessionManager session;
JSONParser jsonParser = new JSONParser();
EditText loc_name, address, city, desc, owner, latitude, longitude;
Spinner category;
Button submit, browse, gps;
String[] items = { "Tulis", "Cap", "Campuran" };
String id_user, tempcate, email, name, phone;
TextView path,status;
String image_name;
private static String url = "http://batiktour.adi-hidayat.com/Android/AddLocation.php";
public static String strUsername;
public static String strLocName;
public static String strCategory;
public static String strAddress;
public static String strCity;
public static String strDesc;
public static String strowner;
public static String strlat;
public static String strLng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_location);
session = new SessionManager(getApplicationContext());
Toast.makeText(getApplicationContext(),
"User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG)
.show();
session.checkLogin();
HashMap<String, String> user = session.getUserDetails();
name = user.get(SessionManager.KEY_NAME);
email = user.get(SessionManager.KEY_USER);
// phone = user.get(SessionManager.KEY_PHONE);
TextView status = (TextView) findViewById(R.id.status);
status.setText(Html.fromHtml(email));
loc_name = (EditText) findViewById(R.id.locName);
address = (EditText) findViewById(R.id.address);
city = (EditText) findViewById(R.id.city);
desc = (EditText) findViewById(R.id.desc);
owner = (EditText) findViewById(R.id.owner);
latitude = (EditText) findViewById(R.id.tvLAT);
longitude = (EditText) findViewById(R.id.tvLNG);
category = (Spinner) findViewById(R.id.category);
submit = (Button) findViewById(R.id.submit);
browse = (Button) findViewById(R.id.browse);
gps = (Button) findViewById(R.id.ubahGPS);
path = (TextView) findViewById(R.id.path);
category = (Spinner)findViewById(R.id.category);
ArrayAdapter aa = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, items);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
category.setAdapter(aa);
category.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
strCategory = items[position];
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mapTambah);
googlemap = fm.getMap();
googlemap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
ImageView img = new ImageView(this);
browse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"), 1);
}
});
gps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
double chgLat;
double chgLng;
chgLat = Double.parseDouble(latitude.getText().toString());
chgLng = Double.parseDouble(longitude.getText().toString());
LatLng latlng = new LatLng(chgLat, chgLng);
googlemap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
googlemap.animateCamera(CameraUpdateFactory.zoomTo(15));
googlemap.addMarker(new MarkerOptions()
.position(latlng)
.title("POSISI")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
}
});
googlemap.setOnMapClickListener(new OnMapClickListener()
{
#Override
public void onMapClick(LatLng latlong)
{
double lat = latlong.latitude;
double lng = latlong.longitude;
latitude.setText(String.valueOf(lat));
longitude.setText(String.valueOf(lng));
MarkerOptions markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latlong);
googlemap.clear();
// Animating to the touched position
googlemap.animateCamera(CameraUpdateFactory.newLatLng(latlong));
// Placing a marker on the touched position
googlemap.addMarker(markerOptions);
}
});
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if(loc_name.getText().toString().trim().length()>0 &&
address.getText().toString().trim().length()>0 &&
city.getText().toString().trim().length()>0 &&
owner.getText().toString().trim().length()>0 &&
desc.getText().toString().trim().length()>0 &&
latitude.getText().toString().trim().length()>0 &&
longitude.getText().toString().trim().length()>0
){
if (path.getText().equals("")) {
Toast.makeText(getApplicationContext(),
"Belum Pilih Gambar", Toast.LENGTH_LONG).show();
} else {
String idUser;
session = new SessionManager(getApplicationContext());
session.checkLogin();
HashMap<String, String> user = session.getUserDetails();
idUser = user.get(SessionManager.KEY_USER);
strUsername = idUser;
strLocName = loc_name.getText().toString();
strAddress = address.getText().toString();
strCity = city.getText().toString();
strDesc = desc.getText().toString();
strowner = owner.getText().toString();
strlat = latitude.getText().toString();
strLng = longitude.getText().toString();
new AddLoc().execute();
}
}
else
{
Toast.makeText(getApplicationContext(), "Isilah yang kosong", Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public void onLocationChanged(Location location) {
EditText tvLAT = (EditText) findViewById(R.id.tvLAT);
EditText tvLNG = (EditText) findViewById(R.id.tvLNG);
Button gps = (Button) findViewById(R.id.ubahGPS);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googlemap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googlemap.animateCamera(CameraUpdateFactory.zoomTo(15));
googlemap.addMarker(new MarkerOptions().position(latLng)
.title("You're Here"));
tvLAT.setText(String.valueOf(latitude));
tvLNG.setText(String.valueOf(longitude));
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
// currImageURI is the global variable I’m using to hold the
// content:
currImageURI = data.getData();
path.setText(getRealPathFromURI(currImageURI));
}
}
}
// Convert the image URI to the direct file system path of the image file
#SuppressWarnings("deprecation")
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
android.database.Cursor cursor = managedQuery(contentUri, proj,
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
class AddLoc extends AsyncTask<String, String, String> {
String hasil,success;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AddLocation.this);
pDialog.setMessage("Menyimpan...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
HttpUploader uploader = new HttpUploader();
try {
image_name = uploader.execute(getRealPathFromURI(currImageURI)).get();
} catch (InterruptedException e) {
Log.e("note1", "upload");
hasil="Interupasi terdapat kesalahan";
Log.e("kesalahan", hasil);
finish();
} catch (ExecutionException e) {
Log.e("note1", "upload2");
hasil="Eksekusi terdapat kesalahan";
Log.e("kesalahan", hasil);
finish();
}
return image_name;
}
protected void onPostExecute(String notifikasi) {
pDialog.dismiss();
Intent dash = new Intent(AddLocation.this,Dashboard.class);
startActivity(dash);
}
}
}
The culprit is most likely related to this line:
image_name = uploader.execute(getRealPathFromURI(currImageURI)).get();
You're firing an AsyncTask from inside another AsyncTask, and the first one blocks until the second is completed. But, from the documentation:
Starting with HONEYCOMB, tasks are executed on a single thread to
avoid common application errors caused by parallel execution.
Since the second task never gets to start (in Android >= 3.0), the first one never gets to finish.
You could fix this by using executeOnExecutor(THREAD_POOL_EXECUTOR)...
... but I would suggest changing your code. Since the first task does nothing (i/o, networking) that would need a background thread, that code can just run in the UI thread. Provide the second (now, only) task with a callback to call in onPostExecute() when it has the result. See android asynctask sending callbacks to ui for a good example of this pattern.
Using get() on AsyncTasks is rarely a good idea.

Pass values of array inbetween classes

I am using a spinner when selected starts an intent and the class that is started gets and XML feed and displays it.
I am trying to call a different XML file based on what is selected by the user. I am not sure how the value can be passed to my XMLfunctions.java and once selected can the other classes reference that data?
HERE is my Eclipse Package Download
My thourghts were to have a multidimensional array with the titles for the spinner and the coinsiding XML url:
package com.patriotsar;
import android.app.Activity;
import android.content.Intent;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
public class patriosar extends Activity {
private Button goButton;
private String array_spinner[];
String url = "http://www.patriotsar.com";
Intent i = new Intent(Intent.ACTION_VIEW);
Uri u = Uri.parse(url);
Context context = this;
Spinner areaspinner;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
array_spinner=new String[4];
array_spinner[0]="George Washington","gw.xml";
array_spinner[1]="BENJAMIN FRANKLIN","bf.xml";
array_spinner[2]="THOMAS JEFFERSON","tj.xml";
array_spinner[3]="PATRICK HENRY","ph.xml";
goButton = (Button)findViewById(R.id.goButton);
areaspinner = (Spinner) findViewById(R.id.areaspinner);
ArrayAdapter<String> adapter =
new ArrayAdapter<String> (this,
android.R.layout.simple_spinner_item,array_spinner);
areaspinner.setAdapter(adapter);
goButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
try {
// Start the activity
i.setData(u);
startActivity(i);
} catch (ActivityNotFoundException e) {
// Raise on activity not found
Toast.makeText(context, "Browser not found.", Toast.LENGTH_SHORT);
}
}
});
areaspinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int item = areaspinner.getSelectedItemPosition();
if(item != 0){
Intent myIntent = new Intent(patriosar.this, ShowXMLPAR.class);
startActivityForResult(myIntent, 0);
}
else {
// finish();
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
}
I then have a listener that calls an intent ShowXMLPAR.class when an item other then default is selected. The ShowXMLPAR class calls a function from XMLfunctions.java class and then shows the data that is returned. So the second value in the selected array item needs to be passed to to both pages I guess.
ShowXMLPAR.java:
package com.patriotsar;
import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.patriotsar.XMLfunctions;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class ShowXMLPAR extends ListActivity {
private Button backButton;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
backButton = (Button)findViewById(R.id.backButton);
backButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view){
Intent myIntent = new Intent(view.getContext(), patriosar.class);
startActivityForResult(myIntent, 0);
}
});
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
String xml = XMLfunctions.getXML();
Document doc = XMLfunctions.XMLfromString(xml);
int numResults = XMLfunctions.numResults(doc);
if((numResults <= 0)){
Toast.makeText(ShowXMLPAR.this, "Geen resultaten gevonden", Toast.LENGTH_LONG).show();
finish();
}
NodeList nodes = doc.getElementsByTagName("result");
for (int i = 0; i < nodes.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element)nodes.item(i);
map.put("main_content", XMLfunctions.getValue(e, "content"));
map.put("name", XMLfunctions.getValue(e, "name"));
mylist.add(map);
}
//
ListAdapter adapter = new SimpleAdapter(ShowXMLPAR.this, mylist , R.layout.listlayout,
new String[] {"main_content", "name" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
}
}
XMLfunctions.java:
package com.patriotsar;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class XMLfunctions {
public final static Document XMLfromString(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
System.out.println("XML parse error: " + e.getMessage());
return null;
} catch (SAXException e) {
System.out.println("Wrong XML file structure: " + e.getMessage());
return null;
} catch (IOException e) {
System.out.println("I/O exeption: " + e.getMessage());
return null;
}
return doc;
}
/** Returns element value
* #param elem element (it is XML tag)
* #return Element value otherwise empty String
*/
public final static String getElementValue( Node elem ) {
Node kid;
if( elem != null){
if (elem.hasChildNodes()){
for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
if( kid.getNodeType() == Node.TEXT_NODE ){
return kid.getNodeValue();
}
}
}
}
return "";
}
public static String getXML(){
String line = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet("http://www.patriotsar.com/patriot_quotes.xml");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
line = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (MalformedURLException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (IOException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
}
return line;
}
public static int numResults(Document doc){
Node results = doc.getDocumentElement();
int res = -1;
try{
res = Integer.valueOf(results.getAttributes().getNamedItem("count").getNodeValue());
}catch(Exception e ){
res = -1;
}
return res;
}
public static String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return XMLfunctions.getElementValue(n.item(0));
}
}
Sorry I am still learning but am excited to get into more advanced (for me) programming. Any Help would be awesome.
As of now the app works but calls the same xml no matter what.
I'm not following your description very well, but if you are wanting to pass data between Activities via Intents then make sure the data you pass can either be included as an Extra, or if you prefer to send actual objects then make sure your objects implement the Parcelable interface.

Categories