thread and handler call different methods each time - android

I am working on app which communicate the web server. I want two methods which call by thread and also need two handler method, which used to update UI . 1 thread method and handler method need to fetch data and update UI at start of the activity. 2 thread method and handler method need to post back data on server.
How I implement this.
My code of this class...
package com.edoc.doctor;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.edoc.libraries.FetchMedicines;
import com.edoc.libraries.Functions;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class AddPatient extends Activity implements Runnable, OnClickListener
{
public static final String appDoctor = "AppDoctor";
public String KEY_SUCCESS = "success";
private String success;
private ProgressDialog pd;
private JSONObject jsonObj;
private boolean addNewPatient;
private EditText email;
private EditText phone;
private EditText name;
private EditText dob;
private EditText lowBPMedicineInstructions;
private EditText highBPMedicineInstructions;
private EditText hyperLowBPMedicineInstructions;
private EditText hyperHighBPMedicineInstructions;
private Spinner lowBPMedicine;
private Spinner highBPMedicine;
private Spinner hyperLowBPMedicine;
private Spinner hyperHighBPMedicine;
private Button addPatient;
private String strEmail;
private String strPhone;
private String strName;
private String strDob;
private String strLowBPMedicineInstructions;
private String strHighBPMedicineInstructions;
private String strHyperLowBPMedicineInstructions;
private String strHyperHighBPMedicineInstructions;
private String strLowBPMedicine;
private String strHighBPMedicine;
private String strHyperLowBPMedicine;
private String strHyperHighBPMedicine;
private ArrayAdapter<String> dataAdapter;
private ArrayList<String> medicines;
private ArrayList<Integer> medicineIDs;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_patient);
medicines = new ArrayList<String>();
medicineIDs = new ArrayList<Integer>();
addPatient = (Button) findViewById(R.id.ib_add_patient);
addPatient.setOnClickListener(this);
email = (EditText) findViewById(R.id.iet_add_patient_email);
phone = (EditText) findViewById(R.id.iet_add_patient_phone);
name = (EditText) findViewById(R.id.iet_add_patient_name);
dob = (EditText) findViewById(R.id.iet_add_patient_date_of_birth);
lowBPMedicineInstructions = (EditText) findViewById(R.id.iet_low_description);
highBPMedicineInstructions = (EditText) findViewById(R.id.iet_high_description);
hyperLowBPMedicineInstructions = (EditText) findViewById(R.id.iet_hyper_low_description);
hyperHighBPMedicineInstructions = (EditText) findViewById(R.id.iet_hyper_high_description);
lowBPMedicine = (Spinner) findViewById(R.id.isp_low_medicine);
highBPMedicine = (Spinner) findViewById(R.id.high_medicine);
hyperLowBPMedicine = (Spinner) findViewById(R.id.hyper_low_medicine);
hyperHighBPMedicine = (Spinner) findViewById(R.id.hyper_high_medicine);
dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, medicines);
final int did = getID();
// pd = ProgressDialog.show(getApplicationContext(), "Working..", "Connect To Server", true,false);
new Thread(new Runnable()
{
public void run()
{
Functions fun = new Functions();
jsonObj = fun.fetchMedicines(did);
handler.sendEmptyMessage(0);
}
}).start();
}
private Handler handler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
try {
Log.e("try","try");
success = jsonObj.getString("success");
Log.e("success",success);
Log.e("add",""+addNewPatient);
if(success.equals("1") && !addNewPatient)
{
JSONArray m = jsonObj.getJSONArray("medicines");
// looping through All Contacts
for(int i = 0; i < m.length(); i++)
{
JSONObject c = m.getJSONObject(i);
String name = c.getString("medicine");
int id = c.getInt("id");
Log.e("m name",name+" "+id);
medicines.add(name);
medicineIDs.add(id);
}
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
lowBPMedicine.setAdapter(dataAdapter);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
highBPMedicine.setAdapter(dataAdapter);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
hyperLowBPMedicine.setAdapter(dataAdapter);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
hyperHighBPMedicine.setAdapter(dataAdapter);
}
else if(success.equals("1") && addNewPatient)
{
Log.e("success", ""+addNewPatient);
pd.dismiss();
Toast.makeText(getApplicationContext(), "Patient Add Successfully",Toast.LENGTH_LONG).show();
finish();
}
else
{
Toast.makeText(getApplicationContext(), "Server down",Toast.LENGTH_LONG).show();
finish();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
public int getID()
{
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences = getSharedPreferences(appDoctor,mode);
Editor editor = mySharedPreferences.edit();
return mySharedPreferences.getInt("id",0);
}
#Override
public void run()
{
Functions function = new Functions();
jsonObj = function.addPatient(strEmail,strPhone,strName,strDob,strLowBPMedicine
,strHighBPMedicine,strHyperHighBPMedicine,strHyperLowBPMedicine,strLowBPMedicineInstructions
, strHighBPMedicineInstructions, strHyperLowBPMedicineInstructions, strHyperHighBPMedicineInstructions, getID());
addNewPatient = true;
Log.e("run", ""+addNewPatient);
handler.sendEmptyMessage(0);
}
#Override
public void onClick(View v)
{
Log.e("onclick","on click");
strEmail = email.getText().toString();
strPhone = phone.getText().toString();
strName = name.getText().toString();
strDob = dob.getText().toString();
strLowBPMedicine = ""+lowBPMedicine.getSelectedItemPosition();
strHighBPMedicine = ""+highBPMedicine.getSelectedItemPosition();
strHyperLowBPMedicine = ""+hyperLowBPMedicine.getSelectedItemPosition();
strHyperLowBPMedicine = ""+hyperLowBPMedicine.getSelectedItemPosition();
strLowBPMedicineInstructions = lowBPMedicineInstructions.getText().toString();
strHighBPMedicineInstructions = highBPMedicineInstructions.getText().toString();
strHyperLowBPMedicineInstructions = hyperLowBPMedicineInstructions.getText().toString();
strHyperHighBPMedicineInstructions = hyperHighBPMedicineInstructions.getText().toString();
pd = ProgressDialog.show(this, "Working..", "Connect To Server", true,false);
Thread t = new Thread();
t.start();
}
}
This stuck on line 222
form below 3rd statement.
pd = ProgressDialog.show(this, "Working..", "Connect To Server", true,false);

Related

Trigger an event when i return to an Event

Im trying to trigger an event when i return to an activity hitting the back button.
what i want to do is when i go back with the backbutton reload some items. Is there any way to do this?
here is my Main Activity where i want to do the "reload" of data, Some thing like "onResume" or "onReEnter"
package com.example.juanfri.seguridadmainactivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.androidquery.AQuery;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class ActivityTemporadaJson extends AppCompatActivity {
private String Nombre;
private int IdTmdb;
private String Tipo;
private int NumeroTemp;
private DBHelper mydb;
private ProgressDialog pDialog;
public final String API = "5e2780b2117b40f9e4dfb96572a7bc4d";
public final String URLFOTO ="https://image.tmdb.org/t/p/original";
private Temporada temp;
private TextView nombrePelicula;
private ImageView fotoPortada;
private TextView sinopsis;
private TextView NumEpsVal;
private TextView fechaLanzVal;
private ArrayList<Episodio> episodios;
private RecyclerView recyclerView;
private LinearLayoutManager mLinearLayoutManager;
private RecyclerAdapterEpisodio mAdapterEp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_temporada_json);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent recep = this.getIntent();
episodios = new ArrayList<>();
Nombre = recep.getStringExtra("Nombre");
Tipo = recep.getStringExtra("Tipo");
IdTmdb = Integer.parseInt(recep.getStringExtra("idSerie"));
NumeroTemp = Integer.parseInt(recep.getStringExtra("NumTemp"));
this.setTitle(Nombre);
nombrePelicula = (TextView) this.findViewById(R.id.NombrePelicula);
fotoPortada = (ImageView) this.findViewById(R.id.FotoPortada);
sinopsis = (TextView) this.findViewById(R.id.Sinopsis);
NumEpsVal = (TextView) this.findViewById(R.id.NumEpsVal);
fechaLanzVal = (TextView) this.findViewById(R.id.FechaLanzVal);
recyclerView = (RecyclerView) this.findViewById(R.id.recyclerviewEpisodios);
mydb = new DBHelper(this);
if (Tipo.equalsIgnoreCase("SQL")) {
Cursor res = mydb.getResultQuery("SELECT count(e.Visto) as numVisto FROM Episodio e, Temporada t WHERE t.IdTMDB = " + IdTmdb + " and e.IdTemporada = t.IdTemporada and e.NumeroTemporada = " + NumeroTemp + " and e.visto = 1");
res.moveToFirst();
int NumVisto = res.getInt(0);
mydb.UpdateEpsVistos(NumVisto, IdTmdb, NumeroTemp);
TextView NumEpsVis = (TextView) this.findViewById(R.id.EpsVis);
TextView NumEpsVisVal = (TextView) this.findViewById(R.id.EpsVisVal);
NumEpsVis.setVisibility(View.VISIBLE);
NumEpsVisVal.setVisibility(View.VISIBLE);
AQuery androidAQuery = new AQuery(this);
res = mydb.getResultQuery("SELECT Nombre, Sinopsis, FechaInicio, Poster, NumeroEpisodios,EpisodiosVistos FROM Temporada WHERE IdTMDB = " + IdTmdb + " and NumeroTemporada = " + NumeroTemp);
res.moveToFirst();
nombrePelicula.setText(res.getString(0));
sinopsis.setText(res.getString(1));
fechaLanzVal.setText(res.getString(2));
androidAQuery.id(fotoPortada).image(res.getString(3), true, true, 150, 0);
NumEpsVal.setText(Integer.toString(res.getInt(4)));
NumEpsVisVal.setText(Integer.toString(res.getInt(5)));
Cursor resEps = mydb.getResultQuery("SELECT e.Nombre, e.NumeroEpisodio, e.NumeroTemporada, e.FechaEmision, e.Sinopsis, e.Poster, e.Visto, e.IdEpisodio FROM Episodio e, Temporada t WHERE t.IdTMDB = " + IdTmdb + " and e.IdTemporada = t.IdTemporada and e.NumeroTemporada = " + NumeroTemp);
resEps.moveToFirst();
while (resEps.isAfterLast() == false) {
boolean visto = false;
if (resEps.getInt(6) == 1) {
visto = true;
}
Episodio nuevo = new Episodio(resEps.getInt(7), 0, resEps.getString(0), resEps.getInt(1), resEps.getInt(2), resEps.getString(3), resEps.getString(4), resEps.getString(5), visto);
episodios.add(nuevo);
resEps.moveToNext();
}
mLinearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(mLinearLayoutManager);
mAdapterEp = new RecyclerAdapterEpisodio(episodios, IdTmdb, Tipo);
recyclerView.setAdapter(mAdapterEp);
} else {
new GetTemp(this).execute();
}
//mydb = new DBHelper(this);
}
private class GetTemp extends AsyncTask<Void, Void, Void> {
Context c;
public GetTemp(Context c)
{
this.c = c;
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
//url = "https://api.themoviedb.org/3/tv/airing_today?api_key="+API+"&language=en-US&page="+pagina;
//https://api.themoviedb.org/3/tv/57243/season/1?api_key=5e2780b2117b40f9e4dfb96572a7bc4d&language=en-US
String url = "https://api.themoviedb.org/3/tv/"+IdTmdb+"/season/"+NumeroTemp+"?api_key="+API+"&language=es-ES";
String jsonStr = sh.makeServiceCall(url);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray episodes = jsonObj.getJSONArray("episodes");
String fecha = jsonObj.getString("air_date");
String nombreSerie = jsonObj.getString("name");
int numEps = episodes.length();
int numTemp = jsonObj.getInt("season_number");
String sinop = jsonObj.getString("overview");
String poster =URLFOTO + jsonObj.getString("poster_path");
// looping through All Contacts
for (int i = 0; i < episodes.length(); i++) {
JSONObject c = episodes.getJSONObject(i);
Episodio nuevo = new Episodio();
nuevo.setSinopsis(c.getString("overview"));
nuevo.setFechaEmision(c.getString("air_date"));
nuevo.setNombreEpisodio(c.getString("name"));
nuevo.setNumeroEpisodio(c.getInt("episode_number"));
nuevo.setNumeroTemporada(c.getInt("season_number"));
nuevo.setPoster(URLFOTO + c.getString("still_path"));
episodios.add(nuevo);
}
temp = new Temporada(0, IdTmdb, nombreSerie, sinop, fecha, poster, numTemp,false, 0, numEps, episodios);
} catch (final JSONException e) {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
} else {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
AQuery androidAQuery=new AQuery(c);
// Dismiss the progress dialog
if (pDialog.isShowing())
{
pDialog.dismiss();
}
androidAQuery.id(fotoPortada).image(temp.getPoster(), true, true, 150,0);
String Nombre = "Temporada " + temp.getNumeroTemporada();
nombrePelicula.setText(Nombre);
sinopsis.setText(temp.getSinopsis());
NumEpsVal.setText(Integer.toString(temp.getNumeroEpisodios()));
fechaLanzVal.setText(temp.getFechaInicio());
mLinearLayoutManager = new LinearLayoutManager(c, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(mLinearLayoutManager);
mAdapterEp = new RecyclerAdapterEpisodio(temp.getEpisodios(),IdTmdb,Tipo);
recyclerView.setAdapter(mAdapterEp);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(c);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
}
}
You can use onRestart , which will be triggered when existing activity will be bought back to front .
As quoted in docs
Called after onStop() when the current activity is being re-displayed
to the user (the user has navigated back to it). It will be followed
by onStart() and then onResume().
so Override onRestart
#Override
public void onRestart() {
// you come back to me
}

Cannot resolve class in same package, async android development using eclipse

This is my first android project so please excuse my ignorance if I have missed something!
I am trying to change a register form using json/php/mysql into using async, the error I am getting is RegisterTask cannot be resolved to a type on this line
new RegisterTask().execute();
My complete code is this:
package com.app.pubcrawlorganiser;
import org.json.JSONException;
import org.json.JSONObject;
import com.app.pubcrawlorganiser.library.DatabaseHandler;
import com.app.pubcrawlorganiser.library.JSONParser;
import com.app.pubcrawlorganiser.library.UserFunctions;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
#SuppressWarnings("unused")
public class RegisterActivity extends Activity
{
Button btnRegister;
Button btnLinkToLogin;
EditText inputFullName;
EditText inputEmail;
EditText inputPassword;
TextView registerErrorMsg;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
// Importing all assets like buttons, text fields
inputFullName = (EditText) findViewById(R.id.registerName);
inputEmail = (EditText) findViewById(R.id.registerEmail);
inputPassword = (EditText) findViewById(R.id.registerPassword);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
registerErrorMsg = (TextView) findViewById(R.id.register_error);
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
new RegisterTask().execute();
}
}
);
class RegisterTask extends AsyncTask<String, String, String>
{
protected void onPreExecute()
{
super.onPreExecute();
}
protected String doInBackground(String... args)
{
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(name, email, password);
try {
if (json.getString(KEY_SUCCESS) != null)
{
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1)
{
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
Intent dashboard = new Intent(getApplicationContext(), Home.class);
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
finish();
}
else
{
registerErrorMsg.setText("Error occured in registration");
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
return null;
}
};}
protected void onPostExecute()
{
btnLinkToLogin.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent i = new Intent(getApplicationContext(),
WelcomeActivity.class);
startActivity(i);
// Close Registration View
finish();
}
});
}
}
Why cant I use a class in the same package?
You can't define an inner class inside a method! Move it outside onCreate() and it should work.
PS: inner classes should be added at the very top of the outer class or at the very bottom. Depending on your coding rules/guidelines. Placing it somewhere in the middle is pretty confusing...

How to parse an array in json array

I am parsing json but in my jsonarray I have another array and this arrays values have no tags.(property name.) Here is my code. I can parse the other values but not gallery array. How can I parse gallery array's values in onitemclick method? Thanks.
My json link: http://kilimmobilya.com.tr/mobileservices/default.aspx?i=yeniUrunler
My json:
{
"veri": [
{
"id": "1436",
"tarih": "08.10.2012",
"baslik": "Ares Plazma TV \u00dcnitesi",
"kImaj": "http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Plazma-Unitesi/210x120/Ares-Plazma-VS1-00.jpg",
"kisaAciklama": "",
"icerik": "",
"fiyat": "799",
"Gallery": [
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Plazma-Unitesi/630x360/Ares-Plazma-VS1-00.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Plazma-Unitesi/630x360/Ares-Plazma-VS1-01.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Plazma-Unitesi/630x360/Ares-Plazma-VS1-02.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Plazma-Unitesi/630x360/Ares-Plazma-VS2-00.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Plazma-Unitesi/630x360/Ares-Plazma-VS2-01.jpg"
]
},
{
"id": "1434",
"tarih": "08.10.2012",
"baslik": "Ares Yatak Odas\u0131",
"kImaj": "http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/210x120/Ares-Yatak-Odasi-Takim-00.jpg",
"kisaAciklama": "",
"icerik": "",
"fiyat": "5690",
"Gallery": [
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-00.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-00-1.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-01.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-02.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-03.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-04.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-05.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-06.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-07.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-08.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-09.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-10.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-11.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-12.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-13.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-14.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-15.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-16.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-17.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-18.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-19.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-20.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-21.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Yatak-Odasi/630x360/Ares-Yatak-Odasi-Takim-22.jpg"
]
}
package com.eticaret.hakan;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.eticaret.hakan.R;
import android.R.string;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Yeniurunler extends Activity implements OnItemClickListener,OnClickListener {
int gelencatid;
Button altkampanya,altkatalog,altbayi,altiletisim;
private static final String rssFeed = "http://kilimmobilya.com.tr/mobileservices/default.aspx?i=yeniUrunler";
private static final String link="http://salih.arti-sanat.com/e-ticaret/s3.jpg";
private static final String TAG_PRODUCTS = "veri";
private static final String TAG_PID = "id";
private static final String TAG_PNAME = "baslik";
private static final String TAG_PPRICE = "tarih";
private static final String TAG_PDESCRIPTION = "kisaAciklama";
private static final String TAG_CREATEDAT = "tarih";
private static final String TAG_LINK = "kImaj";
private static final String TAG_GALLERY="Gallery";
List<Item> arrayOfList;
ListView listView;
KampanyaRowAdapter objAdapter;
JSONArray jsonArray;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.yeniurunler);
altkampanya=(Button) findViewById(R.id.altkampanyalar);
altkatalog=(Button) findViewById(R.id.altkataloglar);
altbayi=(Button) findViewById(R.id.altbayilerimiz);
altiletisim=(Button) findViewById(R.id.altiletisim);
altkampanya.setOnClickListener(this);
altkatalog.setOnClickListener(this);
altbayi.setOnClickListener(this);
altiletisim.setOnClickListener(this);
listView = (ListView) findViewById(R.id.listview);
listView.setDivider(new ColorDrawable(0x90000000));
listView.setDividerHeight(1);
listView.setOnItemClickListener(this);
arrayOfList = new ArrayList<Item>();
if (Utils.isNetworkAvailable(Yeniurunler.this)) {
new MyTask().execute(rssFeed);
} else {
showToast("Ağ bağlantısı yok!!!");
}
}
// My AsyncTask start...
class MyTask extends AsyncTask<String, Void, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Yeniurunler.this);
pDialog.setMessage("Yükleniyor...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
return Utils.getJSONString(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (null != pDialog && pDialog.isShowing()) {
pDialog.dismiss();
}
if (null == result || result.length() == 0) {
showToast("Ürün Bulunamadı");
Yeniurunler.this.finish();
} else {
try {
JSONObject mainJson = new JSONObject(result);
jsonArray = mainJson.getJSONArray(TAG_PRODUCTS);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject objJson = jsonArray.getJSONObject(i);
Item objItem = new Item();
objItem.setName(objJson.getString(TAG_PNAME));
objItem.setCity(objJson.getString(TAG_PDESCRIPTION));
objItem.setLink(objJson.getString(TAG_LINK));
//objItem.setLink(link);
arrayOfList.add(objItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
// check data...
/*
* for (int i = 0; i < arrayOfList.size(); i++) { Item item =
* arrayOfList.get(i); System.out.println(item.getId());
*
* System.out.println(item.getId());
* System.out.println(item.getName());
* System.out.println(item.getCity());
* System.out.println(item.getGender());
* System.out.println(item.getAge());
* System.out.println(item.getBirthdate()); }
*/
Collections.sort(arrayOfList, new Comparator<Item>() {
public int compare(Item lhs, Item rhs) {
return (lhs.getAge() - rhs.getAge());
}
});
setAdapterToListview();
}
}
}
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent a = new Intent(getApplicationContext(), YeniUrunDetay.class);
// starting new activity and expecting some response back
startActivity(a);
// sending pid to next activity
}
public void setAdapterToListview() {
objAdapter = new KampanyaRowAdapter(Yeniurunler.this, R.layout.kampanyarow,
arrayOfList);
listView.setAdapter(objAdapter);
}
public void showToast(String msg) {
Toast.makeText(Yeniurunler.this, msg, Toast.LENGTH_LONG).show();
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.altkampanyalar:
Intent goAltkampanya= new Intent(this, Kampanyalar.class);
startActivity(goAltkampanya);
break;
case R.id.altkataloglar:
Intent goAltkatalog = new Intent(this, Kataloglar.class);
startActivity(goAltkatalog);
break;
case R.id.altbayilerimiz:
Intent goBAyi= new Intent(this, Bayiler.class);
startActivity(goBAyi);
break;
case R.id.altiletisim:
Intent goAltiletisim= new Intent(this, Iletisim.class);
startActivity(goAltiletisim);
break;
}
}
}
This is your POJO
public class Veri {
private long id;
private String date;
private String baslik;
private String kImagj;
private String kisaAciklama;
private String icerik;
private String fiyat;
private List<String> gallery;
// Constructors, getters and setters…
}
Here is the code to parse
private List<Veri> parseJson(String json) {
List<Veri> veriList = new ArrayList<Veri>();
List<String> galleryImages = new ArrayList<String>();
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray veriArray = jsonObject.getJSONArray("veri");
int nVeri = veriArray.length();
for (int i = 0; i < nVeri; i++) {
JSONObject veriObject = veriArray.getJSONObject(i);
long id = Long.valueOf(veriObject.getString("id"));
String date = veriObject.getString("tarih");
String baslik = veriObject.getString("baslik");
String kImaj = veriObject.getString("kImaj");
String kisaAciklama = veriObject.getString("kisaAciklama");
String icerik = veriObject.getString("icerik");
String fiyat = veriObject.getString("fiyat");
JSONArray galleryImageArray = veriObject.getJSONArray("Gallery");
int nImages = galleryImageArray.length();
for(int j = 0; j < nImages; i++) {
galleryImages.add(galleryImageArray.getString(j));
}
Veri veri = new Veri();
veri.setId(id);
veri.setDate(date);
veri.setBaslik(baslik);
veri.setKImagj(kImaj);
veri.setKisaAciklama(kisaAciklama);
veri.setFiyat(fiyat);
veri.setGallery(galleryImages);
veriList.add(veri);
}
} catch (JSONException e) {
e.printStackTrace();
}
return veriList;
}
This could help!
you can use Gson by defining objects accordingly.
for Arrays, naturally there won't be field names, therefore these can be parsed into List.
here comes an example using the response for this url
http://kilimmobilya.com.tr/mobileservices/default.aspx?i=yeniUrunler
JsonObject in the response array is;
{
id: "1436",
tarih: "08.10.2012",
baslik: "Ares Plazma TV Ünitesi",
kImaj: "http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Plazma-Unitesi/210x120/Ares-Plazma-VS1-00.jpg",
kisaAciklama: "",
icerik: "",
fiyat: "799",
Gallery: [
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Plazma-Unitesi/630x360/Ares-Plazma-VS1-00.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Plazma-Unitesi/630x360/Ares-Plazma-VS1-01.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Plazma-Unitesi/630x360/Ares-Plazma-VS1-02.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Plazma-Unitesi/630x360/Ares-Plazma-VS2-00.jpg",
"http://www.kilimmobilya.com.tr/urunler/PANEL-GRUP/Ares-Plazma-Unitesi/630x360/Ares-Plazma-VS2-01.jpg"
]
},
create a Java object as;
public class Urun implements Serializable {
private static final long serialVersionUID = 1L;
#Expose public String id;
#Expose public String tarih;
#Expose public String baslik;
#Expose public String kImaj;
#Expose public String kisaAciklama;
#Expose public String icerik;
#Expose public String fiyat;
#Expose public List<String> Gallery;// notice this is a List of String
}
then you can easily parse the JsonObject into defined class. example using Gson
Urun urun = (new Gson()).fromJson(jsonObj, Urun.class);
hope this helps...

AsyncTask is not working properly in android 4.0

I have this async Task on android 2.3.5
class InternetConnexionErrorAsync extends AsyncTask<String, String, String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
mdpiImageView.setClickable(false);
journalsImageView.setClickable(false);
accountImageView.setClickable(false);
Toast.makeText(getBaseContext(),errorMessage , Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(String... aurl) {
try {
Thread.sleep(3450);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String unused)
{
finish();
}
}
Everything is working well.
When I try this in Android 4.0, I am newer accessint the onPostExecute.
Could you please help me. No error message, only that the onPostExecute is newer reached.
Whatever you need to update on the UI you need to do in onPostExecute.
The code below, take a look at onPostExecute - specifically the activity.xx() methods send updates to the main activity that do things on the UI.
For example:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import library.DatabaseHandler;
import library.JSONParser;
import library.UserFunctions;
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.json.JSONException;
import org.json.JSONObject;
import com.actionbarsherlock.R;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginTask extends AsyncTask<String, Void, Integer> {
private ProgressDialog progressDialog;
private Polling activity;
private int id = -1;
private JSONParser jsonParser;
private static String loginURL = "http://davidjkelley.net/android_api/";
private static String registerURL = "http://davidjkelley.net/android_api/";
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private int responseCode = 0;
public LoginTask(Polling activity, ProgressDialog progressDialog)
{
this.activity = activity;
this.progressDialog = progressDialog;
}
#Override
protected void onPreExecute()
{
progressDialog.show();
}
protected Integer doInBackground(String... arg0) {
EditText userName = (EditText)activity.findViewById(R.id.emailEditText);
EditText passwordEdit = (EditText)activity.findViewById(R.id.passEditText);
String email = userName.getText().toString();
String password = passwordEdit.getText().toString();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(email, password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
//user successfully logged in
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(activity.getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
//Log.v("name", json_user.getString(KEY_NAME));
// Clear all previous data in database
userFunction.logoutUser(activity.getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL),
json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
responseCode = 1;
// Close Login Screen
//finish();
}else{
responseCode = 0;
// Error in login
}
}
} catch (NullPointerException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
return responseCode;
}
#Override
protected void onPostExecute(Integer responseCode)
{
EditText userName = (EditText)activity.findViewById(R.id.emailEditText);
EditText passwordEdit = (EditText)activity.findViewById(R.id.passEditText);
if (responseCode == 1) {
progressDialog.dismiss();
activity.loginReport(responseCode);
userName.setText("");
passwordEdit.setText("");
//shared prefences, store name
}
if (responseCode == 0) {
progressDialog.dismiss();
activity.loginReport(responseCode);
}
//if(responseCode == 202)
//activity.login(id);
//else
//activity.showLoginError("");
}
}
Here's the main activity, you can see what loginReport does:
public class Polling extends SherlockFragmentActivity {
private ViewPager mViewPager;
private TabsAdapter mTabsAdapter;
private final static String TAG = "21st Polling:";
private Button loginButton;
private Button registerButton;
private CheckBox remember;
SharedPreferences sharedPreferences;
Toast toast;
ActionBar bar;
//DatabaseHandler ;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(TAG, "onCreate");
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.pager);
setContentView(mViewPager);
bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayShowTitleEnabled(false);
bar.setDisplayShowHomeEnabled(false);
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(bar.newTab().setText(R.string.login),
LoginFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.economics),
EconFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.elections),
ElectionsFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.politics),
PoliticsFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.science),
ScienceFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.finance),
FinanceFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.religion),
ReligionFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.military),
MilitaryFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.international),
InternationalFragment.class, null);
}
public void loginReport(int responseCode) {
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
UserFunctions userFunctions = new UserFunctions();
Context context = getApplicationContext();
//login succeeded, sent when LoginTask doInBg sends a 1 to onPostExecute
if (responseCode == 1) {
loginButton = (Button)findViewById(R.id.loginButton);
loginButton.setText("Log Out");
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "Logged in.", duration);
toast.show();
bar.getTabAt(0).setText(db.getUserDetails().get(db.KEY_EMAIL));
//Log.v(TAG, db.getUserDetails().toString());
}
//login failed, sent when LoginTask doInBg sends a 0 to onPostExecute
if (responseCode == 0) {
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "Incorrect username/password", duration);
toast.show();
}
if (responseCode == 2) {
//logout button clicked, listened from within LoginFragment
//remove user from active sql db here rather than LoginFragment?!
bar.getTabAt(0).setText(R.string.login);
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, "Logged out", duration);
toast.show();
userFunctions.logoutUser(context);
}
}
The solution I adopted, after the suggestion of #Davek804 is that I replace the AsyncTask with a delayed runable like this:
private Runnable mMyRunnable = new Runnable()
{
public void run()
{
finish();
}
};
Toast.makeText(getBaseContext(),errorMessage , Toast.LENGTH_LONG).show();
Handler myHandler = new Handler();
myHandler.postDelayed(mMyRunnable, 3450);
So the effect will be the same.
I found the solution here
Instead of using :
task.execute();
use :
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null);

TextViews become single-line instead of multi-line when populated in a thread

I have an Activity that retrieves information from a url. I have 2 textviews which are multi-line (txtTitle & txtContent). If I populate them without using thread, it displays as multi-line. However, when I use a thread, the text views become single-line.
Is there anything I'm missing? Is the UI not completely ready when I tried putting text in it?
My sample code is below:
package com.mysite.app;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.Spanned;
import android.widget.TextView;
public class ViewNewsActivity extends Activity implements Runnable{
private ProgressDialog progressDialog = null;
private String apiUrl = "";
private String title = "";
private String content = "";
private Runnable viewNews;
private TextView txtTitle = null;
private TextView txtContent = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_news);
Intent myIntent = getIntent();
apiUrl = "http://www.mysite.com" + myIntent.getStringExtra("api_url");
Thread thread = new Thread(this);
thread.start();
progressDialog = ProgressDialog.show(ViewNewsActivity.this,
"Please wait...", "Retrieving News ...", true);
}
public void run() {
txtTitle = (TextView)findViewById(R.id.view_news_title);
txtContent = (TextView)findViewById(R.id.view_news_content);
getNews(apiUrl);
handler.sendEmptyMessage(0);
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
progressDialog.dismiss();
txtTitle.setText(title);
Spanned contentHtml = Html.fromHtml(content);
txtContent.setText(contentHtml.toString());
}
};
private void getNews(String apiUrl) {
String result = JSONUtils.getJSONResponse(apiUrl);
JSONObject jsonResponse;
try {
jsonResponse = new JSONObject(result);
title = jsonResponse.getString("title");
content = jsonResponse.getString("content");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Categories

Resources