Skip to content

Commit

Permalink
Aggiunta classe DrawableManager per caching e multithreading immagini
Browse files Browse the repository at this point in the history
aggiunto layout question responsive (Tablet ecc) con relativa action bar
Sistemati i guai di qualcuno sulla score page :)
  • Loading branch information
raffysommy committed Apr 5, 2015
1 parent 84ff3d2 commit df5c332
Show file tree
Hide file tree
Showing 10 changed files with 595 additions and 106 deletions.
151 changes: 151 additions & 0 deletions app/src/main/java/com/example/raffaele/testapp/DrawableManager.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
package com.example.raffaele.testapp;

/**
* Created by Raffaele on 05/04/2015.
* This is a rewrite of android-drawable-manager library provided under MIT licence,so this is provided under MIT licence
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* Questa classe implementa la gestione del download delle immagini in thread indipendenti.
* E' stata estesa per permettere di gestire non solo le imageview ma anche bottoni e imagebutton
* E' stato inoltre sistemato l'algoritmo di caching in memoria delle immagini usante il SoftReference
*/

import java.io.IOException;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.BasicManagedEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;

public class DrawableManager {
private static final String LOG_TAG = "DrawableManager";
protected final Map<String, SoftReference<Drawable>> drawableMap;
protected static DrawableManager _instance;
public static DrawableManager getInstance(){
if(_instance == null) _instance = new DrawableManager();
return _instance;
}

private void setByObject(Drawable drawable,Object view){ //setta il drawable al seconda del tipo e delle api.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
if (view instanceof Button) {
((Button) view).setBackground(drawable);
return;
}
if (view instanceof ImageButton) {
((ImageButton) view).setBackground(drawable);
return;
}
}
else {
if (view instanceof Button) {
((Button) view).setBackgroundDrawable(drawable);
return;
}
if (view instanceof ImageButton) {
((ImageButton) view).setBackgroundDrawable(drawable);
return;
}
}
if(view instanceof ImageView){
((ImageView)view).setImageDrawable(drawable);
return;
}
return;
}

protected DrawableManager() {
drawableMap = new HashMap<String, SoftReference<Drawable>>();
}

public void setDrawable(final String urlString, final Object view){
if(drawableMap.containsKey(urlString)){ //se l'oggetto è in cache ed è valido lo setto altrimenti rimuovo l'url
Drawable drawable = drawableMap.get(urlString).get();
if(drawable != null){
setByObject(drawable,view);
Log.i(LOG_TAG,"Image Cached");
return;
}
else drawableMap.remove(urlString);
}
final HttpClient httpClient = new DefaultHttpClient(); //instanzio httpclient
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
if(msg.obj != null) setByObject((Drawable) msg.obj,view);
}
}; //Handler di settaggio

final Thread thread = new Thread(){
// final int id = millis;
// final HttpClient client = httpClient;
@Override
public void run() { //dichiaro il thread
Log.i(LOG_TAG, urlString);
HttpGet request = new HttpGet(urlString); //Instanzio la richiesta di Get
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 2000);
HttpConnectionParams.setSoTimeout(params, 1000);
request.setParams(params); //passo i parametri di timeout
BasicManagedEntity entity = null;

try{
HttpResponse response = httpClient.execute(request); //scarica l'immagine
entity = (BasicManagedEntity)response.getEntity();
} catch (IOException e) {
handler.sendEmptyMessage(NORM_PRIORITY); //in caso di eccezione termina il thread richiamando l'handler alla priorità di default e stampa lo Stack Trace
e.printStackTrace();
}
if(entity != null){
Drawable drawable = null;
try {
drawable = Drawable.createFromStream(entity.getContent(), "www");
drawableMap.put(urlString,new SoftReference(drawable));
} catch (IOException e) {
handler.sendEmptyMessage(NORM_PRIORITY);
e.printStackTrace();
}
if(drawable == null){
handler.sendEmptyMessage(NORM_PRIORITY);
}
else{
handler.sendMessage(handler.obtainMessage(NORM_PRIORITY,drawable));
}
}
else{
handler.sendEmptyMessage(NORM_PRIORITY);
}
}
};
thread.start(); //fa partire il thread
}

}
21 changes: 13 additions & 8 deletions app/src/main/java/com/example/raffaele/testapp/Question.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.support.v7.app.ActionBarActivity;
Expand All @@ -13,6 +14,7 @@
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
Expand All @@ -30,6 +32,7 @@ public class Question extends ActionBarActivity {
private ArgumentList argumentList=new ArgumentList();
private ArrayList<String[]> scores = new ArrayList<String[]>();
private String id_question;
private DrawableManager draw=new DrawableManager();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Expand Down Expand Up @@ -64,7 +67,7 @@ public Query request_data() {
Query Domand = new Query();
String result;
JSONObject jo;
HTMLRequest htmlRequest = new HTMLRequest(this.api, "access_token=" + this.token +"&Topics="+this.argumentList.toString());
HTMLRequest htmlRequest = new HTMLRequest(this.api, "access_token=" + this.token +"&topics="+this.argumentList.toString());
try {
result = htmlRequest.getHTMLThread();
jo = new JSONObject(result);
Expand Down Expand Up @@ -104,7 +107,7 @@ public boolean onOptionsItemSelected(MenuItem item) {
if (id == R.id.action_settings) {
return true;
}
if(id==R.id.Correct||id==R.id.CorrectIMG||id==R.id.Wrong||id==R.id.WrongImg){
if(id==R.id.CorrectCnt||id==R.id.CorrectImg||id==R.id.WrongCnt||id==R.id.WrongImg){
this.Score_click(this.getCurrentFocus());
}
return super.onOptionsItemSelected(item);
Expand All @@ -131,12 +134,14 @@ public void CambiaBottone(int buttonid, String risp) {
String regtex = "\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
RegEx regex = new RegEx(regtex);
if (regex.Match(risp)) {
HTMLDrawable htmlimg = new HTMLDrawable(risp);
/*HTMLDrawable htmlimg = new HTMLDrawable(risp);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
button.setBackground(htmlimg.getimg());
} else {
button.setBackgroundDrawable(htmlimg.getimg());
}
}*/

draw.setDrawable(risp,findViewById(buttonid));
button.setText(" ");
button.setHint(risp);
} else {
Expand Down Expand Up @@ -164,18 +169,18 @@ public void onClick1(View v) {
Toast.makeText(getApplicationContext(), "Right :)", Toast.LENGTH_SHORT).show();
cambiatestobottoni();//cambia il testo dei bottoni con una nuova domanda
findViewById(R.id.textView3).setVisibility(View.INVISIBLE);
score=(TextView) findViewById(R.id.Correct);
score=(TextView) findViewById(R.id.CorrectCnt);
correct.increment();
score.setText("Correct: "+ correct.toString());
score.setText(correct.toString());

} else {//risposta sbagliata
result = "0";
Toast.makeText(getApplicationContext(), "Wrong!", Toast.LENGTH_SHORT).show();
//ha bisogno di suggerimenti
findViewById(R.id.textView3).setVisibility(View.VISIBLE);
score=(TextView) findViewById(R.id.Wrong);
score=(TextView) findViewById(R.id.WrongCnt);
wrong.increment();
score.setText("Wrong: "+ wrong.toString());
score.setText(wrong.toString());

}
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_score_page);
Intent i = getIntent();
Bundle extras=i.getExtras();
if(this.correct!=null || this.correct!=null) {
if(extras.getParcelable("Correct")!=null || extras.getParcelable("Wrong")!=null) {
//TODO: Qui si dovrebbe inserire il getscore totale se il campo passato non è null (ciru ce pienz tu :) )
this.correct = extras.getParcelable("Correct");
this.wrong = extras.getParcelable("Wrong");
Expand All @@ -25,6 +25,7 @@ protected void onCreate(Bundle savedInstanceState) {
((TextView) findViewById(R.id.WrongC)).setText(wrong.StringValue());
((TextView) findViewById(R.id.AnsweredC)).setText(correct.StringValue());
}

}


Expand Down
96 changes: 96 additions & 0 deletions app/src/main/res/layout-land/activity_question.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.example.raffaele.testapp.Question"
android:id="@+id/textbox1"
android:onClick="Score_click"
android:nestedScrollingEnabled="false">

<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<TextView
android:layout_width="wrap_content"
android:layout_height="60dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="QuestionText"
android:id="@+id/domanda"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="25dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Do you want to repeat this topic?Click here!"
android:id="@+id/textView3"
android:textSize="15dp"
android:visibility="invisible"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:height="25dp" />

<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<Button
android:layout_width="80dp"
android:layout_height="80dp"
android:id="@+id/Risposta1"
android:onClick="onClick1"
android:text=" "
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<Button
android:layout_width="80dp"
android:layout_height="80dp"
android:id="@+id/Risposta2"
android:onClick="onClick1"
android:text=" "
android:layout_gravity="right"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />

<Button
android:layout_width="80dp"
android:layout_height="80dp"
android:id="@+id/Risposta3"
android:onClick="onClick1"
android:text=" "
android:layout_gravity="left|bottom"
android:textSize="35dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<Button
android:layout_width="80dp"
android:layout_height="80dp"
android:id="@+id/Risposta4"
android:onClick="onClick1"
android:text=" "
android:layout_gravity="right|bottom"
android:textSize="35dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>

</LinearLayout>

</RelativeLayout>

Loading

0 comments on commit df5c332

Please sign in to comment.