android App closes with no error when imageview is clicked - java

I am creating a simple imageview with an id and trying to start an activity when it is clicked but when i click it in the emulator, the app just crashes and gives me (wait or close the app prompt)
here is my:
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:orientation="vertical">
<ImageView
android:id="#+id/about"
android:layout_width="match_parent"
android:layout_height="450dp"
android:background="#color/colorPrimaryDark"
android:src="#drawable/twoth" />
</LinearLayout>
and here is my java code
public class MainUi extends AppCompatActivity {
//Variables Declaration.
private Button btn1, btn2, btn3, btn4;
private ImageView img;
//Called when the activity is first created.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_ui);
//Variables Initialization and OnClick Method
img = (ImageView) findViewById(R.id.about);
img.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Start another activity
Intent myIntent = new Intent(MainUi.this, Query.class);
startActivity(myIntent);
}
});
}
}

The 'wait or close' thing leads me to think there's something in Query activity that is doing a lot of work on the main thread.
Try to use an AsyncTask and put all your long running processes in the doInBackground part and later handle the response in the onPostExecute.
I guess it depends a lot of what you are actually doing, but AsyncTask should be a good start.

here is the full code, I added the rest of the code just in case you can handle it from the outer (Query) class and not within Async Class.
public class Query extends AppCompatActivity {
private ArrayList<String[]> BB;
private ArrayList<String[]> AA = new ArrayList<String[]>();
private Socket socket = null;
private ObjectInputStream in = null;
private DataOutputStream out = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_query);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
try {
AA = new AsyncAction().execute().get();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
setTextViews();
}
}
public void setTextViews() {
View linearLayout = findViewById(R.id.info);
for (int y = 0; y < AA.size(); y++) {
// for (int x = 0; x < AA.get(0).length; x++) {}
TextView name = new TextView(this);
name.setText(AA.get(y)[0]);
name.setId(y);
name.setGravity(Gravity.CENTER);
name.setTextSize(30);
name.setPadding(0, 30, 0, 0);
name.setTextColor(this.getResources().getColor(R.color.icons));
name.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0));
ProgressBar pb = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);
Drawable drawable = pb.getProgressDrawable();
drawable.setColorFilter(new LightingColorFilter(0xFF000000, this.getResources().getColor(R.color.colorPrimary)));
pb.setProgress(100);
final int finalY = y;
name.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Bundle b = new Bundle();
b.putStringArray("list", AA.get(finalY));
Intent i = new Intent(Query.this, Info.class);
i.putExtras(b);
startActivity(i);
}
});
((LinearLayout) linearLayout).addView(name);
((LinearLayout) linearLayout).addView(pb);
}
}
private class AsyncAction extends AsyncTask<String, Void, ArrayList> {
protected ArrayList doInBackground(String... args) {
try {
socket = new Socket(port, 8888);
out = new DataOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());
// action
out.writeInt(2);
try {
in = new ObjectInputStream(socket.getInputStream());
BB = (ArrayList<String[]>) in.readObject();
in.close();
socket.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return BB;//returns what you want to pass to the onPostExecute()
}
protected void onPostExecute(ArrayList result) {
AA = result;
}
}
}

Related

Swipe Refresh freezes when executing async task

I'm encountering a problem, when I try running an asynchronous task on refresh using a swipe refresh layout it "freezes" and doesn't rotate. When the task is done it just disappears.
Here is my code:
HotActivityFragment.java:
public class HotActivityFragment extends Fragment {
ListView hotList;
SwipeRefreshLayout mSwipeRefreshLayout;
Context context;
SharedPreferences sharedPreferences;
HotListAdapter hotListAdapter;
public HotActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_hot, container, false);
context = getContext();
mSwipeRefreshLayout = (SwipeRefreshLayout)view.findViewById(R.id.activity_main_swipe_refresh_layout);
hotList = (ListView)view.findViewById(R.id.hotListView);
hotList.setOnScrollListener(new EndlessScrollListener(getActivity()));
sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
try {
ArrayList<ListTypeItem> initial_list = new DownloadPosts(getActivity()).execute().get();
this.hotListAdapter = new HotListAdapter(getContext(), initial_list);
hotList.setAdapter(hotListAdapter);
}catch(Exception e)
{
Log.d("Download Error", e.toString());
}
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
retrievePosts();
}
});
mSwipeRefreshLayout.setColorSchemeResources(R.color.accentColor, R.color.backgroundColor);
return view;
}
public void retrievePosts()
{
// showing refresh animation before making http call
mSwipeRefreshLayout.setRefreshing(true);
//shared preferences = empty
sharedPreferences.edit().putString("last_time_downloaded", "empty").commit();
try {
ArrayList<ListTypeItem> listItems = new DownloadPosts(getActivity(), mSwipeRefreshLayout).execute().get();
hotListAdapter.updateList(listItems);
hotListAdapter.notifyDataSetChanged();
} catch (Exception e) {
Log.d("Download Error", e.toString());
}
mSwipeRefreshLayout.setRefreshing(false);
//for testing purposes
// new Handler().postDelayed(new Runnable() {
// #Override public void run() {
// mSwipeRefreshLayout.setRefreshing(false);
// }
// }, 5000);
}
}
DownloadPosts.java:
public class DownloadPosts extends AsyncTask<Void, Void, ArrayList<ListTypeItem>> {
SharedPreferences sharedPreferences;
SwipeRefreshLayout swipeRefreshLayout;
public DownloadPosts(Activity activity)
{
this.sharedPreferences = activity.getPreferences(Context.MODE_PRIVATE);
}
public DownloadPosts(Activity activity, SwipeRefreshLayout swipeRefreshLayout)
{
this.sharedPreferences = activity.getPreferences(Context.MODE_PRIVATE);
this.swipeRefreshLayout = swipeRefreshLayout;
}
#Override
protected ArrayList<ListTypeItem> doInBackground(Void... args)
{
StringBuilder parsedString = new StringBuilder();
ArrayList<ListTypeItem> downloadList = new ArrayList<>();
StringBuilder str = new StringBuilder();
if(sharedPreferences.getBoolean("Thomas More",false))
{
str.append("190155257998823,");
}
String school_url = str.toString();
if(school_url.length() > 0)
{
school_url = school_url.substring(0, str.length()-1);
}
try{
String date = "";
//checken of opnieuw moet bepaald worden
// + in de adapter moet als gereload wordt last_time_downloaded == empty
if(!sharedPreferences.getString("last_time_downloaded","empty").equals("empty"))
{
String last_date = sharedPreferences.getString("last_time_downloaded","nothing");
last_date = last_date.replace(" ","T");
date= "&datum_last_posted=" + last_date;
}
URL url = new URL("http://localhost/getpostlist.php?school_post=" + school_url + date);
URLConnection conn = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String json;
while((json = bufferedReader.readLine())!= null)
{
parsedString.append(json + "/n");
}
String s = parsedString.toString().trim();
//converten van string opgehaald via http naar jsonobject
JSONArray array = new JSONArray(s);
for(int i = 0; i < array.length(); i++)
{
JSONObject tempObj = array.getJSONObject(i);
School_WithoutImage tempSchool = new School_WithoutImage(tempObj.getString("school_id"),
tempObj.getString("post_message"),tempObj.getInt("views"),tempObj.getInt("likes")
,tempObj.getInt("post_id"),tempObj.getString("datum_posted"));
downloadList.add(tempSchool);
if(i == array.length()-1) {
sharedPreferences.edit().putString("last_time_downloaded",tempObj.getString("datum_posted")).commit();
}
}
JSONObject obj = array.getJSONObject(0);
}catch(Exception e)
{
Log.d("Exception", e.toString());
}
return downloadList;
}
#Override
protected void onPostExecute(ArrayList<ListTypeItem> result)
{
if(this.swipeRefreshLayout != null)
{
// swipeRefreshLayout.setRefreshing(false);
}
}
}
I have no idea why the swiperefreshview doesn't spin. Anyone has an idea?
Because the call to get():
.execute().get()
Forces the UI thread to wait for the AsyncTask to finish.
Instead you should look at doing this in the onPostExecute method:
protected void onPostExecute(ArrayList<ListTypeItem> listItems) {
hotListAdapter.updateList(listItems);
hotListAdapter.notifyDataSetChanged();
}
Because you are waiting for the result from asynctask by calling get just after execute. And further passing it to list.
You can use Local Broadcast Listener or can create an interface and can us that as callback, without freezing UI

Reading and writing a serialized object in android

I've been searching on here but can't seem to find what works. I'm trying to write a simple object list to a serialized file and can't seem to locate the file in android. It's my first time building an app and I had this working in netbeans by pointing to src/list.ser, however, this doesn't work in android studio. I guess my question is where do I place the ser file and how do I point to it in the code? Here is my code:
ListActivity:
public class ListActivity extends Activity implements Serializable {
private ArrayList<Item> list;
public List() throws Exception {
list = new ArrayList<Item>();
}
public void addItem(String name) {
list.add(new Item(name));
}
public void addCurrentList() throws Exception{
String pathToAppFolder = getExternalFilesDir(null).getAbsolutePath();
String filePath = pathToAppFolder +File.separator + "list.ser";
try {
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(filePath));
os.writeObject(list);
os.close();
}
catch (Exception e) {
System.out.println("NOPE NOPE NOPE NOPE");
}
}
public void addItem(String name, int price) {
list.add(new Item(name, price));
}
public ArrayList<Item> populate() {
return list;
}
public void record() {
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream("src/list.ser"));
ArrayList<Item> list2 = (ArrayList<Item>) in.readObject();
System.out.println(list2);
list = list2;
in.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
private List tester;
private ListView lv;
private EditText gg;
private Button button;
private Button clearButton;
private ArrayList list;
String pathToAppFolder = getExternalFilesDir(null).getAbsolutePath();
String filePath = pathToAppFolder + File.separator + "list.ser";
#Override
protected void onDestroy() {
try {
tester.addCurrentList();
} catch (Exception e) {
e.printStackTrace();
}
super.onDestroy();
}
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//create the list
lv = (ListView) findViewById(R.id.listDisplay);
ListView mine = lv;
list = new ArrayList<String>();
try {
tester = new List();
}
catch (Exception e) {
}
for (Item item : tester.populate()) {
list.add(item);
}
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,list);
lv.setAdapter(arrayAdapter);
final TextView firstTextView = (TextView) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);
clearButton = (Button) findViewById(R.id.clear);
gg = (EditText) findViewById(R.id.item);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String no = gg.getText().toString();
if (!no.isEmpty()) {
tester.addItem(no);
arrayAdapter.add(no);
arrayAdapter.notifyDataSetChanged();
gg.setText("");
}
}
});
clearButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
arrayAdapter.clear();
arrayAdapter.notifyDataSetChanged();
}
});
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = lv.getItemAtPosition(position).toString();
arrayAdapter.remove(arrayAdapter.getItem(position));
arrayAdapter.notifyDataSetChanged();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
First of all make sure that you have permission to write to the external storage.
as,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
You can use,
public void addCurrentList() throws Exception{
String pathToAppFolder = getExternalFilesDir(null).getAbsolutePath();
String filePath = pathToAppFolder +File.seperator + "list.ser";
try {
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(filePath));
os.writeObject(list);
os.close();
}
catch (Exception e) {
System.out.println("");
}
}
and the use create a file path from that as,
String filePath = pathToAppFolder +File.seperator + "Test.text";
and then where ever you want to read this file again, you can recreate the path. Because you have access to the context from the android code
EDIT
You can not access the context as you do in your code. You can do it in your onCreate method. I have added only the necessary parts.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pathToAppFolder = getExternalFilesDir(null).getAbsolutePath();
filePath = pathToAppFolder + File.separator + "list.ser";
//create the list
Oh my god, I had to go into great lengths to answer your question. Here it is, Your List class is not an Activity in your application. It is just a class. So I suggest you to remove those inheritance first. remove this extends Activity. And I suggest you to change the List class name to something else. Because, List is a defined keyword and its not a best practice to do so.
Change the method in List Activity as below.
public void addCurrentList(String filePath) throws Exception
try {
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(filePath));
os.writeObject(list);
os.close();
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
public void record(String filePath) {
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(filePath));
ArrayList<Item> list2 = (ArrayList<Item>) in.readObject();
System.out.println(list2);
list = list2;
in.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
In your MainActivity, onDestroy Method,
change the code to,
tester.addCurrentList(filePath);

How can I check by a button click which ip to connect?

On the MainActivity.java I have a method that connect with a server:
private byte[] Get(String urlIn)
{
URL url = null;
String urlStr = urlIn;
if (urlIn!=null)
urlStr=urlIn;
try
{
url = new URL(urlStr);
} catch (MalformedURLException e)
{
e.printStackTrace();
return null;
}
HttpURLConnection urlConnection = null;
try
{
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
byte[] buf=new byte[10*1024];
int szRead = in.read(buf);
byte[] bufOut;
if (szRead==10*1024)
{
throw new AndroidRuntimeException("the returned data is bigger than 10*1024.. we don't handle it..");
}
else
{
bufOut = Arrays.copyOf(buf, szRead);
}
return bufOut;
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
finally
{
if (urlConnection!=null)
urlConnection.disconnect();
}
}
I'm calling this method from onTouchEvent():
#Override
public boolean onTouchEvent(MotionEvent event)
{
float eventX = event.getX();
float eventY = event.getY();
float lastdownx = 0;
float lastdowny = 0;
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
path.moveTo(eventX, eventY);
circlePath.addCircle(eventX, eventY, 50, Path.Direction.CW);
lastdownx = eventX;
lastdowny = eventY;
Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
byte[] response = null;
if (is_start == true)
{
response = Get("http://10.0.0.2:8098/?cmd=start");
is_start = false;
}
else
{
response = Get("http://10.0.0.2:8098/?cmd=stop");
is_start = true;
}
if (response!=null)
{
String a = null;
try
{
a = new String(response,"UTF-8");
textforthespeacch = a;
MainActivity.currentActivity.initTTS();
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
Logger.getLogger("MainActivity(inside thread)").info(a);
}
}
});
t.start();
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(eventX, eventY);
break;
case MotionEvent.ACTION_UP:
circlePath.reset();
break;
default:
return false;
}
invalidate();
return true;
}
So now i'm connecting all the time to 10.0.0.2:8098
But that's when i connect my android device on my network on my pc room.
But if i move to the living room and connect to the network there a differenet network with another pc the pc ip is differenet in this case: 10.0.0.3:8099
So i added a button click event to the MainActivity.java:
public class MainActivity extends ActionBarActivity
{
private static final int MY_DATA_CHECK_CODE = 0;
public static MainActivity currentActivity;
TextToSpeech mTts;
private String targetURL;
private String urlParameters;
private Button btnClick;
private String clicking = "clicked";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
currentActivity = this;
initTTS();
}
public void addListenerOnButton() {
btnClick = (Button) findViewById(R.id.checkipbutton);
btnClick.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
}
});
}
Inside the button click event I want to check after connected to the network with a wifi if the pc ip is 10.0.0.3:8099 or 10.0.0.2:8098
I need that it will try to connect to this servers and if success then to set to a global variable global string the ip.
I added a global variable: string ipaddress
Now i use static address in my code but i need to check which ip address is correct and then to set this ip to the variable which i will use later in my code as the ip address.
How do I make the checking in the button click event ?
This is what i tried now:
At the top of my MainActivity i added:
private final String[] ipaddresses = new String[2];
private final Integer[] ipports = new Integer[2];
Socket socket = null;
Then in the onCreate:
ipaddresses[0] = "10.0.0.3";
ipaddresses[1] = "10.0.0.2";
ipports[0] = 8098;
ipports[1] = 8088;
addListenerOnButton();
new Thread(new ClientThread()).start();
Then
public void addListenerOnButton() {
btnClick = (Button) findViewById(R.id.checkipbutton);
btnClick.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
try {
String str = btnClick.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
And the ClientThread
class ClientThread implements Runnable {
#Override
public void run() {
for (int i=0; i<ipaddresses.length; i++)
{
try
{
InetAddress serverAddr = InetAddress.getByName(ipaddresses[i]);
socket = new Socket(serverAddr, ipports[i]);
} catch (UnknownHostException e1)
{
e1.printStackTrace();
} catch (IOException e1)
{
e1.printStackTrace();
}
}
}
}
This is a screenshot of the exception message i'm getting:
The exception is on the line:
new OutputStreamWriter(socket.getOutputStream())),
You must open sockets to check server connectivity. Here is an example on you send strings to server on click event:
public class Client extends Activity {
private Socket socket;
private static final int SERVERPORT = 8099;
private static final String SERVER_IP = "10.0.0.3";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new Thread(new ClientThread()).start();
}
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
So if you get an exception trying to connect to server, it means you haven't connectivity.

Why is there too much work on main thread?

So I'm trying to make a simple application that makes stores group events in a MySQL database then retrieves them for people to join. In this fragment I list all the events by using a JSONParser class to query the database. I use an Async class to do the querying. The fragment will initially query the db on startup or whenever the user decides to limit the scope of the events by selecting something in a spinner or when the user pushes a refresh button. I have been getting messages like
Choreographer﹕ Skipped 95 frames! The application may be doing too much work on its main thread.
while running the program and I'm not sure why. I think it might be because I call the Async class too much, but I'm not sure.
public class mainActivityFragment extends Fragment {
final public String information = "information";
public Spinner specifySubject;
private ArrayList<String> list = new ArrayList<>();
private ArrayList<EventObject> eventList = new ArrayList<>();
JSONParser jsonParser = new JSONParser();
ListView test;
ArrayAdapter adapter;
// url to create new product
private static String url_get_event = "";
private ProgressDialog pDialog;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_main, container, false);
adapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1, list);
test = (ListView) v.findViewById(R.id.listView);
new CreateNewProduct().execute();
if(pDialog.isShowing()){
pDialog.dismiss();
}
test.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
Intent in = new Intent(getActivity(), AttendInformation.class);
EventObject clickedEvent = eventList.get(position);
String[] testInformation = {clickedEvent.getTo().toString(), clickedEvent.getLocation(), clickedEvent.getTitle(), clickedEvent.getDurationString(), clickedEvent.getDescription(), clickedEvent.getSubject()};
in.putExtra(information, testInformation);
startActivity(in);
}
});
Button createEventButton = (Button) v.findViewById(R.id.Button2);
createEventButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent in = new Intent(getActivity(), createEvent.class);
startActivity(in);
}
});
specifySubject = (Spinner) v.findViewById(R.id.spinner);
specifySubject.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
AsyncTask task;
task = new CreateNewProduct().execute();
try {
task.get(3000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
if (position == 0) {
} else {
String selectedSubj = getResources().getStringArray(R.array.class_array)[position];
for (int i = 0; i < eventList.size(); i++) {
if (!eventList.get(i).getSubject().equals(selectedSubj)) {
list.remove(list.indexOf(eventList.get(i).getTitle()));
eventList.remove(i);
i--;
}
}
adapter.notifyDataSetChanged();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Button refresh = (Button) v.findViewById(R.id.leftButton);
refresh.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AsyncTask task;
task = new CreateNewProduct().execute();
try {
task.get(3000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
if (specifySubject.getSelectedItemPosition() == 0) {
} else {
String selectedSubj = getResources().getStringArray(R.array.class_array)[specifySubject.getSelectedItemPosition()];
for (int i = 0; i < eventList.size(); i++) {
if (!eventList.get(i).getSubject().equals(selectedSubj)) {
list.remove(list.indexOf(eventList.get(i).getTitle()));
eventList.remove(i);
i--;
}
}
adapter.notifyDataSetChanged();
}
}
});
return v;
}
class CreateNewProduct extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Getting Events...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
JSONArray jsonArr = jsonParser.getJSONFromUrl(url_get_event);
for(int n = 0; n < jsonArr.length(); n++)
{
try {
JSONObject object = jsonArr.getJSONObject(n);
if(!list.contains(object.getString("title"))){
String[] time = object.getString("time").split(":");
time[1] = time[1].substring(0, 2);
EventObject tempEven = new EventObject(object.getString("title"), object.getString("location"), object.getString("description"), object.getString("subject"), 0, new TimeObject(Integer.parseInt(time[0]), Integer.parseInt(time[1])));
eventList.add(tempEven);
list.add(object.getString("title"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
test.setAdapter(adapter);
pDialog.dismiss();
}
}
}

Unable to show and hide ProgressBar during download in action

I've created an app which by clicking on a list Item, downloads an image from the Internet on a button click (also it places the url on to the EditText for user to see what the url is).
Initially I'm setting the ProgressBar and TextView (indicating Loading....) in a hide mode. But as the download starts, I would like to bring both TextView and ProgressBar on to the UI and once the download completes, would like to make both of them invisible.
There is NO error message on the LogCat to post. I believe I'm missing something which is tricky :). Let me know if any additional information is required. Thanks SO in advance.
Below is the XML: for LinearLayout which should be ON/OFF
<LinearLayout
android:id="#+id/loadingSection"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/downloadImage"
android:visibility="gone"
android:orientation="vertical" >
<TextView
android:id="#+id/loadingMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Loading....."
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceSmall" />
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:indeterminate="true" />
</LinearLayout>
And below is the Java file:
public class DownloadImages_HandlerMainActivity extends Activity implements OnItemClickListener {
private EditText editText;
private ListView listView;
private TextView textView;
private String[] listOfImages;
private Button downloadImage;
private ProgressBar progressBar;
private LinearLayout loadingSection = null;
private Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.downloadimages_main);
editText = (EditText) findViewById(R.id.downloadURL);
textView = (TextView) findViewById(R.id.loadingMessage);
listView = (ListView) findViewById(R.id.urlList);
downloadImage = (Button) findViewById(R.id.downloadImage);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
listOfImages = getResources().getStringArray(R.array.imageURLs);
listView.setOnItemClickListener(this);
handler = new Handler();
}
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
editText.setText(listOfImages[position]);
}
public void downloadImage(View view) {
String url = editText.getText().toString();
Thread myThread = new Thread(new DownloadImagesThread(url));
myThread.start();
}
public boolean downloadImageUsingThreads(String url) {
boolean successful = false;
URL downloadURL = null;
HttpURLConnection connection = null;
InputStream inputStream = null;
File file = null;
FileOutputStream fileOutputStream = null;
try {
downloadURL = new URL(url);
connection = (HttpURLConnection) downloadURL.openConnection();
inputStream = connection.getInputStream();
file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).getAbsolutePath()
+ "/" + Uri.parse(url).getLastPathSegment());
fileOutputStream = new FileOutputStream(file);
int read = -1;
byte[] buffer = new byte[1024];
while ((read = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, read);
//Log.d("BRK0018", " " + read);
successful = true;
}
} catch (MalformedURLException e) {
e.printStackTrace();
Log.d("BRK0018", " " + e);
} catch (IOException e) {
e.printStackTrace();
Log.d("BRK0018", " " + e);
} finally {
// This is the HANDLER INSTANCE in place of thread
handler.post(new Runnable() {
#Override
public void run() {
try {
loadingSection.setVisibility(View.GONE); // Making the ProgressBar INVISIBLE
} catch (Exception e) {
Log.d("BRK0018", " " + e);
}
}
});
if (connection != null) {
connection.disconnect();
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
Log.d("BRK0018", " " + e);
}
}
}
return successful;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class DownloadImagesThread implements Runnable {
private String url;
public DownloadImagesThread(String url) {
this.url = url;
}
// This is the HANDLER INSTANCE in place of thread
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
try {
// TODO Auto-generated method stub
loadingSection.setVisibility(View.VISIBLE); // Making the ProgressBar VISIBLE
} catch (Exception e) {
Log.d("BRK0018", " " + e);
}
}
});
downloadImageUsingThreads(url);
}
}
}
The problem here is loadingSection which is null. And since you change its visibility in try/catch block, the app doesn't crash. Initialize the layout in onCreate():
loadingSection = (LinearLayout) findViewById(R.id.loadingSection);
First of all, when you call
handler.post(new Runnable() {
#Override
public void run() {
try {
// TODO Auto-generated method stub
loadingSection.setVisibility(View.VISIBLE);
Thread.sleep(1000);
} catch (Exception e) {
Log.d("BRK0018", " " + e);
}
}
});
Handler.class runs above code in UI thread.
You must not call Thread.sleep(1000) in UI thread.
(but anyway remember that loadingSection.setVisibility(View.VISIBLE); must be called in UI thread)
Fix it. And whether it helps or not write me.

Categories