Decreasing the time to load from one activity to another activity? - android

I want to optimize my code to reduce the run time of my application. Currently it takes 18secs to load and show the welcome screen.
I am using AsyncTask to put all of my operation(JSON parsing, Database operations). Is there any else method that I can use to shave off at least 4secs from my application.
I can show the code if you want. Please let me know.
Thanking you
I've shared the code here please go through it.
public class MainActivity extends Activity {
/** THE FOLLOWING STRINGS WILL BE DISPLAYED IN LOGCAT */
final String TAG = "##--MAIN ACTIVITY--##";
UserHelper userAdapter;
Context context;
String regName="";
int duration = Toast.LENGTH_LONG;
String regNameSplit[];
JSONObject second_jsonObj = null;
JSONObject jsonObj = null;
JSONObject jsonobj = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
userAdapter = new UserHelper(this);
context = getApplicationContext();
final EditText edit_password = (EditText)findViewById(R.id.password);
final EditText edit_username = (EditText)findViewById(R.id.user_name);
final EditText edit_company = (EditText)findViewById(R.id.company_string);
final Button login = (Button)findViewById(R.id.login_button);
login.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
/*THE IF STATEMENT CHECKS IF THE FIELDS ARE EMPTY OR NOT*/
if (edit_username.getText().toString().equals("") || edit_username.getText().toString() == null ||
edit_password.getText().toString().equals("") || edit_password.getText().toString() == null||
edit_company.getText().toString().equals("") ||edit_company.getText().toString() == null ){
Log.i(TAG,"User has left some fields empty");
Toast.makeText(getApplicationContext(), "Enter all details", duration).show();
} else{
jsonobj = new JSONObject();
try{
//THE TRY STATEMENT CREATES A NEW JSON OBJECT TO BE PARSED IN HANDLEJSON METHOD//
JSONObject subJson = new JSONObject();
subJson.put("username", edit_username.getText().toString()/*"da"*/);
subJson.put("password", edit_password.getText().toString()/*"exicom"*/);
subJson.put("company", edit_company.getText().toString()/*"utb17"*/);
jsonobj.put("user", subJson);
Log.i(TAG,""+jsonobj);
}
catch(JSONException e) {
Log.i("","#####-----error at catch jsonexception-----#####");
}
//JSON OBJECT IS PARSED OVER HERE //
new synchronizeData(URL, jsonobj).execute();
}
}
});
}
class synchronizeData extends AsyncTask<Void, String, Void>{
private String name1;
private String company1;
private String password1;
private String regnaMe1;
private String reg1name1;
ProgressDialog PD ;
public synchronizeData(String name, String password, String company,
String regnaMe, String reg1name) {
// TODO Auto-generated constructor stub
this.name1 = name;
this.company1 = company;
this.password1 = password;
this.regnaMe1 = regnaMe;
this.reg1name1 = reg1name ;
}
public synchronizeData(String uRL, JSONObject jsonobj) {
// TODO Auto-generated constructor stub
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
Log.v(TAG,"Start of doInBackground");
try{
//Log.v(TAG,"The url is ********* "+URL);
//Log.v(TAG, "Json object request is "+jsonobj.toString());
DefaultHttpClient httpClientInstance = GetHttpClient.getHttpClientInstance();
HttpPost httpPostRequest = new HttpPost(URL);
Log.v(TAG,"The url is ********* "+URL);
StringEntity se;
se = new StringEntity(jsonobj.toString());
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");
long t = System.currentTimeMillis();
HttpResponse response = (HttpResponse) httpClientInstance.execute(httpPostRequest);
//Log.i(TAG, "HTTPRESPONSE RECIEVED in " +(System.currentTimeMillis()-t) + "ms");
String resultString = convertStreamToString(response.getEntity().getContent());
//Log.v(TAG ,/* "The response is "resultString);
jsonObj = new JSONObject(resultString);
JSONObject sessionJson = jsonObj.getJSONObject("session");
String sessionId = sessionJson.getString("sessionid");
String name = sessionJson.getString("name");
//Log.v(TAG,"The session ID is "+sessionId);
//Log.v(TAG,"The name is "+name);
regName = name+"-"+sessionId+"-"+URL;
} catch (JSONException e){
try{
Log.i(TAG,"JSON EXCEPTION FIRST");
JSONObject messageJson = jsonObj.getJSONObject("message");
String typeJson = messageJson.getString("type");
String contentJson = messageJson.getString("content");
regName = contentJson;
e.printStackTrace();
}catch(JSONException jse){
jse.printStackTrace();
}catch(Exception ee){
ee.printStackTrace();
}
}catch(Exception ee){
ee.printStackTrace();
}
Log.v(TAG,"before the return statement "+regName.toString());
//return regName;
try{
String regNameSplit[] = regName.split("-");
if(regNameSplit[0].equals("Invalid username or password")){
Toast.makeText(getApplicationContext(), ""+regNameSplit[0], duration).show();
}
else{
String regnaMe = regNameSplit[0].toString();
String reg1name = regNameSplit[1].toString();
Log.v(regnaMe,reg1name);
Intent intent = new Intent(MainActivity.this, Secondactivity.class);
intent.putExtra("regName", regNameSplit[0]);
intent.putExtra("regName_sessionID", regNameSplit[1]);
intent.putExtra("regName_URL", regNameSplit[2]);
startActivity(intent);
}
userAdapter.openDatabase();
//-------------THE DATABASE CHECKS IF THE VALUE IS PRESENT OR NOT IF TRUE DOESN'T INSERT-----------//
if(db.Exists(name1) == true){
} else {
long id = db.insertIntoDatabase(name1,company1,password1,regnaMe1,reg1name1);
Log.i(TAG, "Printing value of id which will be inserted only to remove warnings "+id);
}
}
catch(SQLiteException e){
e.printStackTrace();
}
return null;
}
private java.lang.String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try{
while((line = reader.readLine()) !=null ){
sb.append(line + "\n");
}
}
catch (IOException e){
e.printStackTrace();
} finally{
try {
is.close();
} catch (IOException e){
e.printStackTrace();
}
}
return sb.toString();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
PD = new ProgressDialog(MainActivity.this);
PD.setMessage("Please wait....");
PD.show();
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
PD.dismiss();
userAdapter.closeDatabase();
}
}
}
This is the code for the second activity:
String ht = "";
public final String TAG = "###---Secondactivity---###";
public String reg_name = "";
public String resultString = "";
// AccessTimeReportTableHelper dB;
JSONObject jsonobj = null;
Vector objVector = new Vector();
String bufferedValue = "";
String newdeletedtrsArray = "";
String newschemaArray = "";
String newtrsArray = "";
String URL_ = "";
AccessTimeReportTableHelper useradapter_TimeReportTable;
AccessMessageTable useradapterMessageTable;
AccessMessageTypeTable useradapterMessageTypeTable;
UserHelper userHelper;
AccessTimeReportMessage useradapterTimeReportMessage;
String[] split_newdeletedtrsArray;
String[] split_newschemaArray;
String[] split_newtrsArray;
String[] splitno1_split_newtrsArray;
ArrayList<GetSetMethod> bulk = new ArrayList<GetSetMethod>();
ProgressDialog PD;
#SuppressWarnings({ "rawtypes", "unused" })
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondactivity);
Log.v(TAG, "Start of second activity");
userHelper = new UserHelper(this);
useradapterMessageTable = new AccessMessageTable(this);
useradapter_TimeReportTable = new AccessTimeReportTableHelper(this);
useradapterMessageTypeTable = new AccessMessageTypeTable(this);
useradapterTimeReportMessage = new AccessTimeReportMessage(this);
if (getIntent().getStringExtra("regName") != null) {
try {
String name = getIntent().getStringExtra("regName");
String session_ID = getIntent().getStringExtra(
"regName_sessionID");
URL_ = "URL inserted here";
jsonobj = new JSONObject("custom JSON OBJECT HERE");
String ht = URL_ + "&" + jsonobj;
// Log.i("" + ht, "");
JSONObject jsonObj = null;
String resultString = "";
String deletedtrsArray = "";
String newtrsArray = "";
String newschemaArray = "";
String bufferedValue = "";
Log.v(TAG, "The url is " + URL_);
Log.v(TAG, "Json object request is " + jsonobj.toString());
new AsyncSecondActivity(jsonobj).execute();
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception en) {
en.printStackTrace();
}
}
Log.v(TAG, "Ending program execution here");
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
class AsyncSecondActivity extends AsyncTask<Void, String, Void> {
private String newcompanyid1;
private String newdate1;
private String newusername1;
private String newClientId1;
private String newprojectId1;
private String newniV1;
private String newniV2;
private String newworktypeid1;
private String newtimetypeid1;
private String newhours1;
private String newcomment1;
private String newprivatecomment1;
private String newopen1;
private String newreportid1;
String messageTypeId = "";
String messageConcat = "";
String concatCursorCompare = "";
String newcompanyid;
String date_id = "";
String compareId = "";
String newusername = "";
String newdate = "";
String newClientId = "";
String newprojectId = "";
String newniv1 = "";
String newniv2 = "";
String newworktypeid = "";
String newtimetypeid = "";
String newhours = "";
String newcomment = "";
String newprivatecomment = "";
String newopen = "";
String newreportid = "";
String dateId = "";
String messageType_System = "";
String message_content = "";
String userId_FirstActivity = "";
String date = "";
String report = "";
// Cursor DECLARATION//
Cursor c = null;
Cursor cur = null;
Cursor curMessageTable = null;
Cursor curMessageName = null;
Cursor curMainActivity = null;
Cursor curTimeReportMessage = null;
public AsyncSecondActivity(JSONObject jsonobj) {
Log.v(TAG, "Value of BULK in AsyncSecondActivity (GETSET METHOD) "
+ jsonobj);
}
#Override
protected Void doInBackground(Void... params) {
try{
DefaultHttpClient httpClientInstance = GetHttpClient
.getHttpClientInstance();
HttpPost httpPostRequest = new HttpPost(URL_);
Log.v(TAG, "The url is " + URL_);
StringEntity se;
se = new StringEntity(jsonobj.toString());
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");
long t = System.currentTimeMillis();
HttpResponse response = (HttpResponse) httpClientInstance
.execute(httpPostRequest);
Log.i(TAG,
"HTTPRESPONSE RECIEVED in "
+ (System.currentTimeMillis() - t) + "ms");
resultString = convertStreamToString(response.getEntity()
.getContent());
// Log.v(TAG , "The response is " +resultString);
jsonobj = new JSONObject(resultString);
JSONObject sync_reponse = jsonobj.getJSONObject("syncresponse");
String synckey_string = sync_reponse.getString("synckey");
JSONArray createdtrs_array = sync_reponse
.getJSONArray("createdtrs");
JSONArray modtrs_array = sync_reponse.getJSONArray("modtrs");
// -----HANDLING MODTRS-----//
for (int n = 0; n < modtrs_array.length(); n++) {
JSONObject object = modtrs_array.getJSONObject(n);
String newcompanyID_mod = object.getString("companyid");
String newusername_mod = object.getString("username");
String newdate_mod = object.getString("date");
String newclientid_mod = object.getString("clientid");
String newprojectid_mod = object.getString("projectid");
String newniv1_mod = object.getString("niv1");
String newniv2_mod = object.getString("niv2");
String newworktypeid_mod = object.getString("worktypeid");
String newtimetypeid_mod = object.getString("timetypeid");
String newhours_mod = object.getString("hours");
String newcomment_mod = object.getString("comment");
String newprivatecomment_mod = object
.getString("privatecomment");
String newopen_mod = object.getString("open");
if ((object.has("message"))) {
JSONObject messaget = object.getJSONObject("message");
String newtype = object.getJSONObject("message")
.getString("type");
String newcontent = object.getJSONObject("message")
.getString("content");
GetSetMethod objSample = new GetSetMethod();
objSample.setnewclientid_mod(newclientid_mod);
objSample.setnewusername_mod(newusername_mod);
objSample.setnewdate_mod(newdate_mod);
objSample.setnewprojectid_mod(newprojectid_mod);
objSample.setNewniv1(newniv1_mod);
objSample.setNewniv2(newniv2_mod);
objSample.setNewworktypeid(newworktypeid_mod);
objSample.setNewtimetypeid(newtimetypeid_mod);
objSample.setNewhours(newhours_mod);
objSample.setNewcomment(newcomment_mod);
objSample.setNewopen(newopen_mod);
objSample.setNewprivatecomment(newprivatecomment_mod);
}
}
JSONArray deletedtrs_array = sync_reponse
.getJSONArray("deletedtrs");
// -----------------------HANDLING
// DELETEDTRS------------------------//
for (int n = 0; n < deletedtrs_array.length(); n++) {
JSONObject object = deletedtrs_array.getJSONObject(n);
String newUserName = object.getString("username");
String newCompanyId = object.getString("companyid");
String newDate = object.getString("date");
String newReportId = object.getString("reportid");
}
JSONArray newtrs_array = sync_reponse.getJSONArray("newtrs");
// -----------------------HANDLING
// NEWTRS----------------------------//
GetSetMethod objSample = null;
for (int n = 0; n < newtrs_array.length(); n++) {
JSONObject object = newtrs_array.getJSONObject(n);
String newcompanyid = object.getString("companyid");
String newusername = object.getString("username");
String newdate = object.getString("date");
String newClientId = object.getString("clientid");
String newprojectId = object.getString("projectid");
String newniv1 = object.getString("niv1");
String newniv2 = object.getString("niv2");
String newworktypeid = object.getString("worktypeid");
String newtimetypeid = object.getString("timetypeid");
String newhours = object.getString("hours");
String newcomment = object.getString("comment");
String newprivatecomment = object
.getString("privatecomment");
String newopen = object.getString("open");
String newreportid = object.getString("reportid");
String newcontent_mod = "";
String newtype_mod = "";
if ((object.has("message"))) {
JSONObject message = object.getJSONObject("message");
newtype_mod = object.getJSONObject("message")
.getString("type");
newcontent_mod = object.getJSONObject("message")
.getString("content");
// objSample = new GetSetMethod();
// objSample.setnewcontent_mod(newcontent_mod);
// objSample.setnewtype_mod(newtype_mod);
}
objSample = new GetSetMethod();
objSample.setNewcompanyid(newcompanyid);
objSample.setNewusername(newusername);
objSample.setNewdate(newdate);
objSample.setNewClientId(newClientId);
objSample.setNewprojectId(newprojectId);
objSample.setNewniv1(newniv1);
objSample.setNewniv2(newniv2);
objSample.setNewworktypeid(newworktypeid);
objSample.setNewtimetypeid(newtimetypeid);
objSample.setNewhours(newhours);
objSample.setNewcomment(newcomment);
objSample.setNewprivatecomment(newprivatecomment);
objSample.setNewopen(newopen);
objSample.setNewreportid(newreportid);
if ((newcontent_mod) != null || (newtype_mod) != null) {
objSample.setnewcontent_mod(newcontent_mod);
objSample.setnewtype_mod(newtype_mod);
}
bulk.add(objSample);
objSample.getNewClientId();
for (int i = 0; i < objVector.size(); i++) {
GetSetMethod objtest = new GetSetMethod();
objtest = (GetSetMethod) objVector.get(i);
objtest.getNewClientId();
objtest.getNewcompanyid();
}
}
//new AsyncSecondActivity(bulk).execute();
// -----------------------HANDLING
// SCHEMA-------------------------//
JSONArray schema_array = sync_reponse.getJSONArray("schema");
for (int n = 0; n < schema_array.length(); n++) {
JSONObject object = schema_array.getJSONObject(n);
String new_yearmonth = object.getString("yearmonth");
String new_hoursperday = object.getString("hoursperday");
}
} catch(JSONException e){
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HashMap<String, String> recordExist = new HashMap<String, String>();
userHelper.openDatabase();
useradapter_TimeReportTable.openDatabase();
useradapterMessageTable.openDatabase();
useradapterMessageTypeTable.openDatabase();
useradapterTimeReportMessage.openDatabase();
curMainActivity = userHelper.retrieveUserId();
cur = useradapter_TimeReportTable.getUniqueRecordsId();
curMessageTable = useradapterMessageTable.getMessageTable();
curMessageName = useradapterMessageTypeTable.getMessageTypeId();
for (int i = 0; i < bulk.size(); i++) {
GetSetMethod objtest = bulk.get(i);
this.newcompanyid1 = objtest.getNewcompanyid();
this.newusername1 = objtest.getNewusername();
this.newworktypeid1 = objtest.getNewworktypeid();
this.newniV2 = objtest.getNewniv2();
this.newniV1 = objtest.getNewniv1();
this.newdate1 = objtest.getNewdate();
this.newClientId1 = objtest.getNewClientId();
this.newprojectId1 = objtest.getNewprojectId();
this.newtimetypeid1 = objtest.getNewtimetypeid();
this.newhours1 = objtest.getNewhours();
this.newcomment1 = objtest.getNewcomment();
this.newprivatecomment1 = objtest.getNewprivatecomment();
this.newopen1 = objtest.getNewopen();
this.newreportid1 = objtest.getNewreportid();
this.message_content = objtest.getnewcontent_mod();
this.messageType_System = objtest.getnewtype_mod();
concatCursorCompare = date + "-" + report;
//Log.v("Line number 408: SecondActivity", "Value: " + date);
//Log.v("Line number 409: SecondActivity", "Value: " + report);
recordExist.put(concatCursorCompare, concatCursorCompare);
compareId = objtest.getNewdate() + "-"
+ objtest.getNewreportid();
if (!recordExist.containsValue(compareId)) {
long id = useradapter_TimeReportTable
.insertIntoDatabase(newcompanyid1,
newusername1, newdate1, newClientId1,
newprojectId1, newniV1, newniV2,
newworktypeid1, newtimetypeid1,
newhours1, newcomment1,
newprivatecomment1, newopen1,
newreportid1, userId_FirstActivity);
}
if (cur.moveToFirst()) {
do {
date = cur.getString(cur.getColumnIndexOrThrow("dateId"));
report = cur.getString(cur.getColumnIndexOrThrow("reportId"));
}
while(cur.moveToNext());
}
if (curMessageName.moveToFirst()) {
messageTypeId = curMessageName.getString(curMessageName
.getColumnIndex("messageTypeId"));
}
else {
if (messageType_System != null && messageType_System != "") {
long ins_msg_typ_tbl = useradapterMessageTypeTable
.insertintoMessageTypeName(messageType_System);
curMessageName = useradapterMessageTypeTable.recordExistsmessageTypeTable(messageType_System);
if (curMessageName.moveToFirst()) {
messageTypeId = curMessageName.getString(curMessageName
.getColumnIndex("messageTypeId"));
}
}
}
if (curMainActivity.moveToFirst()) {
userId_FirstActivity = curMainActivity
.getString(curMainActivity
.getColumnIndexOrThrow("userId"));
}
concatCursorCompare = date + "-" + report;
Log.v("Line number 408: SecondActivity", "Value: " + date);
Log.v("Line number 409: SecondActivity", "Value: " + report);
recordExist.put(concatCursorCompare, concatCursorCompare);
compareId = objtest.getNewdate() + "-"
+ objtest.getNewreportid();
}
for (int i = 0; i < bulk.size(); i++) {
GetSetMethod objtest = bulk.get(i);
this.newcompanyid1 = objtest.getNewcompanyid();
this.newusername1 = objtest.getNewusername();
this.newworktypeid1 = objtest.getNewworktypeid();
this.newniV2 = objtest.getNewniv2();
this.newniV1 = objtest.getNewniv1();
this.newdate1 = objtest.getNewdate();
this.newClientId1 = objtest.getNewClientId();
this.newprojectId1 = objtest.getNewprojectId();
this.newtimetypeid1 = objtest.getNewtimetypeid();
this.newhours1 = objtest.getNewhours();
this.newcomment1 = objtest.getNewcomment();
this.newprivatecomment1 = objtest.getNewprivatecomment();
this.newopen1 = objtest.getNewopen();
this.newreportid1 = objtest.getNewreportid();
this.message_content = objtest.getnewcontent_mod();
this.messageType_System = objtest.getnewtype_mod();
try {
compareId = objtest.getNewdate() + "-"
+ objtest.getNewreportid();
if(message_content != null && message_content !=""){
long insertMessageTable = useradapterMessageTable.insertintoMessageTable(messageTypeId,message_content);
}
if(message_content != null && message_content !="" && report!=null && report != ""){
long insertTimeReportMessage = useradapterTimeReportMessage.insertintoTimeReportMessgeTable(report, messageTypeId, date);
}
}catch (Exception e) {
e.printStackTrace();
} finally {
if (curMainActivity != null) {
curMainActivity.close();
curMainActivity = null;
}
if (c != null) {
c.close();
c = null;
}
if (cur != null) {
cur.close();
cur = null;
}
if (curMessageTable != null) {
curMessageTable.close();
curMessageTable = null;
}
if (curMessageName != null) {
curMessageName.close();
curMessageName = null;
}
if(curTimeReportMessage != null){
curTimeReportMessage.close();
curTimeReportMessage = null;
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) throws SQLiteException {
super.onPostExecute(result);
PD.dismiss();
userHelper.closeDatabase();
useradapter_TimeReportTable.closeDatabase();
useradapterMessageTable.closeDatabase();
useradapterMessageTypeTable.closeDatabase();
useradapterTimeReportMessage.closeDatabase();
Toast.makeText(getApplicationContext(),
"Welcome " + getIntent().getStringExtra("regName"),
Toast.LENGTH_LONG).show();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
PD = new ProgressDialog(Secondactivity.this);
PD.setTitle("Please wait");
PD.setMessage("Updating records");
PD.show();
} catch (Exception progressDialog) {
progressDialog.printStackTrace();
}
}
}
}
To put in simple terms I will take a username password and insert it into the database. After I get a JSON response from webservice (got by sending the username and password) I parse the JSON object to a string and then insert it into the database.
In the second activity I obtain a JSON response that I parse and convert the input to a string. I then insert the JSON response into their respective databases.

Emulator is slow - normal device could be much faaster. One potential source for delay woud be UserHelper Object creation - you provided no source code for it. You also omited code for onResume() methods of your activities. Best way to find where performance has gone, would be to perform profiling run with ddms.

Related

Text in textview is not showing strings from java file - openweathermap

I am trying to use openweathermap to get basic data about weather and paste it into textview, but strings to which I am getting data doesn't refresh texts in textviews.
Code:
#SuppressLint("StaticFieldLeak")
class DownloadJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection httpURLConnection;
InputStream inputStream;
InputStreamReader inputStreamReader;
StringBuilder result = new StringBuilder();
try {
url = new URL(strings[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
inputStream = httpURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
int data = inputStreamReader.read();
while (data != -1) {
result.append((char) data);
}
} catch (IOException e) {
e.printStackTrace();
}
return result.toString();
}
}
txtCity = findViewById(R.id.txtCity);
txtTemp = findViewById(R.id.txtTemp);
DownloadJSON downloadJSON = new DownloadJSON();
try {
String result = downloadJSON.execute(url).get();
JSONObject jsonObject = new JSONObject(result);
String temp = jsonObject.getJSONObject("main").getString("temp");
String feel_like = jsonObject.getJSONObject("main").getString("feels_like");
txtCity.setText(City);
txtValueFeelLike.setText(feel_like);
txtTemp.setText(temp);
} catch (ExecutionException | InterruptedException | JSONException e) {
e.printStackTrace();
}
}
'''
String City = "Warsaw";
String url = "http://api.openweathermap.org/data/2.5/weather?q="+City+"&units=metric&appid=eace0bd8251cf6ab043ab9858b796256";
TextView txtCity, txtValueFeelLike, txtTemp;
What am I doing wrong?
Ok, I made a change, tried to make it from the scratch again, but now with onPostExecute(). Still nothing...
public class Weather {
private static final String OPEN_WEATHER_MAP_URL =
"http://api.openweathermap.org/data/2.5/weather?q=Warsaw&units=metric&appid=eace9b6857889076855263cfdb5707c0d00";
public interface AsyncResponse {
void processFinish(String output1, String output2, String output3, String output4, String output5, String output6);
}
public static class placeIdTask extends AsyncTask<String, Void, JSONObject> {
public AsyncResponse delegate = null;//Call back interface
#Override
protected JSONObject doInBackground(String... params) {
JSONObject jsonWeather = null;
try {
jsonWeather = getWeatherJSON();
} catch (Exception e) {
Log.d("Error", "Cannot process JSON results", e);
}
return jsonWeather;
}
#Override
public void onPostExecute(JSONObject json) {
try {
if(json != null){
JSONObject details = json.getJSONArray("weather").getJSONObject(0);
JSONObject main = json.getJSONObject("main");
DateFormat df = DateFormat.getDateTimeInstance();
String city = json.getString("name").toUpperCase(Locale.US) + ", " + json.getJSONObject("sys").getString("country");
String description = details.getString("description").toUpperCase(Locale.US);
#SuppressLint("DefaultLocale") String temperature = String.format("%.2f", main.getDouble("temp"))+ "°";
String humidity = main.getString("humidity") + "%";
String pressure = main.getString("pressure") + " hPa";
String updatedOn = df.format(new Date(json.getLong("dt")*1000));
delegate.processFinish(city, description, temperature, humidity, pressure, updatedOn);
}
} catch (JSONException e) {
}
}
}
public static JSONObject getWeatherJSON() {
try {
URL url = new URL(OPEN_WEATHER_MAP_URL);
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
StringBuilder json = new StringBuilder(1024);
String tmp = "";
while ((tmp = reader.readLine()) != null)
json.append(tmp).append("\n");
reader.close();
JSONObject data = new JSONObject(json.toString());
// This value will be 404 if the request was not
// successful
if (data.getInt("cod") != 200) {
return null;
}
return data;
} catch (Exception e) {
return null;
}
}}
And Main Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cityField = (TextView) findViewById(R.id.city_field);
updatedField = (TextView) findViewById(R.id.updated_field);
detailsField = (TextView) findViewById(R.id.details_field);
currentTemperatureField = (TextView) findViewById(R.id.current_temperature_field);
humidity_field = (TextView) findViewById(R.id.humidity_field);
pressure_field = (TextView) findViewById(R.id.pressure_field);
Weather.placeIdTask asyncTask = new Weather.placeIdTask() {
public void processFinish(String weather_city, String weather_description, String weather_temperature, String weather_humidity, String weather_pressure, String weather_updatedOn) {
cityField.setText(weather_city);
updatedField.setText(weather_updatedOn);
detailsField.setText(weather_description);
currentTemperatureField.setText(weather_temperature);
humidity_field.setText("Humidity: " + weather_humidity);
pressure_field.setText("Pressure: " + weather_pressure);
}
};
No idea what to do now.

How to get All Registered users, not only my contact lists on Firebase in my code

I have this FetchMyUsersService Class, This class gets only users on my contact list, how i can get all Firebase users ? Please Help.
This is my Code
This is Dont written by me.
I Have more classes, but i think this my solution in this class, If not just tell me i share another classes on this project
public class FetchMyUsersService extends IntentService {
private static String EXTRA_PARAM1 = "my_id";
private static String EXTRA_PARAM2 = "token";
private HashMap<String, Contact> myContacts;
private ArrayList<User> myUsers;
private String myId, idToken;
public static boolean STARTED = false;
public FetchMyUsersService() {
super("FetchMyUsersService");
}
public static void startMyUsersService(Context context, String myId, String idToken) {
Intent intent = new Intent(context, FetchMyUsersService.class);
intent.putExtra(EXTRA_PARAM1, myId);
intent.putExtra(EXTRA_PARAM2, idToken);
context.startService(intent);
}
#Override
protected void onHandleIntent(Intent intent) {
STARTED = true;
myId = intent.getStringExtra(EXTRA_PARAM1);
idToken = intent.getStringExtra(EXTRA_PARAM2);
fetchMyContacts();
broadcastMyContacts();
fetchMyUsers();
broadcastMyUsers();
STARTED = false;
}
private void broadcastMyUsers() {
if (this.myUsers != null) {
Intent intent = new Intent(Helper.BROADCAST_MY_USERS);
intent.putParcelableArrayListExtra("data", this.myUsers);
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
localBroadcastManager.sendBroadcast(intent);
}
}
private void fetchMyUsers() {
myUsers = new ArrayList<>();
try {
StringBuilder response = new StringBuilder();
URL url = new URL(FirebaseDatabase.getInstance().getReference().toString() + "/" + Helper.REF_USERS + ".json?auth=" + idToken);
URLConnection conn = url.openConnection();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
response.append(line).append(" ");
}
rd.close();
JSONObject responseObject = new JSONObject(response.toString());
Gson gson = new GsonBuilder().create();
Iterator<String> keys = responseObject.keys();
while (keys.hasNext()) {
String key = keys.next();
JSONObject innerJObject = responseObject.getJSONObject(key);
User user = gson.fromJson(innerJObject.toString(), User.class);
if (User.validate(user) && !user.getId().equals(myId)) {
String idTrim = Helper.getEndTrim(user.getId());
if (myContacts.containsKey(idTrim)) {
user.setNameInPhone(myContacts.get(idTrim).getName());
myUsers.add(user);
}
}
if (myUsers.size() == myContacts.size()) {
break;
}
}
Collections.sort(myUsers, new Comparator<User>() {
#Override
public int compare(User user1, User user2) {
return user1.getNameToDisplay().compareToIgnoreCase(user2.getNameToDisplay());
}
});
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
private void broadcastMyContacts() {
if (this.myContacts != null) {
new Helper(this).setMyUsersNameCache(myContacts);
Intent intent = new Intent(Helper.BROADCAST_MY_CONTACTS);
intent.putExtra("data", this.myContacts);
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
localBroadcastManager.sendBroadcast(intent);
}
}
private void fetchMyContacts() {
myContacts = new HashMap<>();
Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if (cursor != null && !cursor.isClosed()) {
cursor.getCount();
while (cursor.moveToNext()) {
int hasPhoneNumber = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhoneNumber == 1) {
String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).replaceAll("\\s+", "");
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY));
if (Patterns.PHONE.matcher(number).matches()) {
boolean hasPlus = String.valueOf(number.charAt(0)).equals("+");
number = number.replaceAll("[\\D]", "");
if (hasPlus) {
number = "+" + number;
}
Contact contact = new Contact(number, name);
String endTrim = Helper.getEndTrim(contact.getPhoneNumber());
if (!myContacts.containsKey(endTrim))
myContacts.put(endTrim, contact);
}
}
}
cursor.close();
}
}
}
Please try changing the code of your fetchMyUsers() like bellow
private void fetchMyUsers() {
myUsers = new ArrayList<>();
try {
StringBuilder response = new StringBuilder();
URL url = new URL(FirebaseDatabase.getInstance().getReference().toString() + "/" + Helper.REF_USERS + ".json?auth=" + idToken);
URLConnection conn = url.openConnection();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
response.append(line).append(" ");
}
rd.close();
JSONObject responseObject = new JSONObject(response.toString());
Gson gson = new GsonBuilder().create();
Iterator<String> keys = responseObject.keys();
while (keys.hasNext()) {
String key = keys.next();
JSONObject innerJObject = responseObject.getJSONObject(key);
User user = gson.fromJson(innerJObject.toString(), User.class);
myUsers.add(user);
if (myUsers.size() == myContacts.size()) {
break;
}
}
Collections.sort(myUsers, new Comparator<User>() {
#Override
public int compare(User user1, User user2) {
return user1.getNameToDisplay().compareToIgnoreCase(user2.getNameToDisplay());
}
});
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}

How to Pass Context OF one Activity to Another Non Activity Class In Android

hello i want to get string from activity and set it to the another non activity class please help me i am adding my code.and i need to set the edittext value in non activity class url. help me
my activity.
public class AlertForIp extends AppCompatActivity {
String value;
private Button mButton;
final Context c = this;
static String urlString;
private static AlertForIp instance;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog);
instance = this;
final EditText input = new EditText(AlertForIp.this);
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(AlertForIp.this);
//AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
/* SharedPreferences prefss = PreferenceManager.getDefaultSharedPreferences(AlertForIp.this);
final SharedPreferences.Editor editor = prefss.edit();*/
value = input.getText().toString();
// Setting Dialog Title
String urlsss="http://";
String urls=":1219/Json/Handler.ashx";
// This above url string i need to set in that class
urlString = urlsss+value+urls;
/* editor.putString("stringid", urlString); //InputString: from the EditText
editor.commit();
*/
alertDialog.setTitle("WELCOME TO RESTROSOFT");
// Setting Dialog Message
alertDialog.setMessage("ENTER YOUR IP");
//final EditText input = new EditText(this);
//alertDialog.setView(input);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
//input.setText("http://");
InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter() {
#Override
public CharSequence filter(CharSequence source, int start, int end,
android.text.Spanned dest, int dstart, int dend) {
if (end > start) {
String destTxt = dest.toString();
String resultingTxt = destTxt.substring(0, dstart)
+ source.subSequence(start, end)
+ destTxt.substring(dend);
if (!resultingTxt
.matches("^\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3})?)?)?)?)?)?")) {
return "";
} else {
String[] splits = resultingTxt.split("\\.");
for (int i = 0; i < splits.length; i++) {
if (Integer.valueOf(splits[i]) > 255) {
Toast.makeText(AlertForIp.this, "Please enter valid ip", Toast.LENGTH_SHORT).show();
return "";
}
}
}
}
return null;
}
};
input.setFilters(filters);
//input.setText(ip);
alertDialog.setView(input); //
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.waiting);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
/*if(input.getText().length()==0)
{
input.setError("Field cannot be left blank.");
dialog.dismiss();
}*/
String validation="^\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3})?)?)?)?";
if (value.matches(validation))
{
Toast.makeText(getApplicationContext(),"enter valid IP address",Toast.LENGTH_SHORT).show();
Intent inten = new Intent(AlertForIp.this, AlertForIp.class);
startActivity(inten);
// or
}
else if(!input.getText().toString().equals(""))
{
Intent intent = new Intent(AlertForIp.this, Sample.class);
startActivity(intent);
//Toast.makeText(AlertDialogForIp.this, "Input Text Is Empty.. Please Enter Some Text", Toast.LENGTH_SHORT).show();
}
else
{
Intent inten = new Intent(AlertForIp.this, AlertForIp.class);
startActivity(inten);
Toast.makeText(AlertForIp.this, "Input Text Is Empty.. Please Enter Some Text", Toast.LENGTH_SHORT).show();
}
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog
//dialog.cancel();
finish();
}
});
// closed
// Showing Alert Message
alertDialog.show();
}
public static Context getContext() {
RestAPI rss=new RestAPI();
rss.persistItems(urlString);
return instance.getApplicationContext();
}
}
And here is my no activity class
public class RestAPI {
String urlString;
//String data;
public void persistItems(String info) {
Context context = AlertForIp.getContext();
/* SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
data = prefs.getString("stringid", "no id");*/
urlString=info;
}
//private final String urlString = "http://10.0.2.2:1219/Json/Handler.ashx";
private static String convertStreamToUTF8String(InputStream stream) throws IOException {
String result = "";
StringBuilder sb = new StringBuilder();
try {
InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[4096];
int readedChars = 0;
while (readedChars != -1) {
readedChars = reader.read(buffer);
if (readedChars > 0)
sb.append(buffer, 0, readedChars);
}
result = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
private String load(String contents) throws IOException {
//i want to add that urlstring here;
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(60000);
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStreamWriter w = new OutputStreamWriter(conn.getOutputStream());
w.write(contents);
w.flush();
InputStream istream = conn.getInputStream();
String result = convertStreamToUTF8String(istream);
return result;
}
private Object mapObject(Object o) {
Object finalValue = null;
if (o.getClass() == String.class) {
finalValue = o;
} else if (Number.class.isInstance(o)) {
finalValue = String.valueOf(o);
} else if (Date.class.isInstance(o)) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss", new Locale("en", "USA"));
finalValue = sdf.format((Date) o);
} else if (Collection.class.isInstance(o)) {
Collection<?> col = (Collection<?>) o;
JSONArray jarray = new JSONArray();
for (Object item : col) {
jarray.put(mapObject(item));
}
finalValue = jarray;
} else {
Map<String, Object> map = new HashMap<String, Object>();
Method[] methods = o.getClass().getMethods();
for (Method method : methods) {
if (method.getDeclaringClass() == o.getClass()
&& method.getModifiers() == Modifier.PUBLIC
&& method.getName().startsWith("get")) {
String key = method.getName().substring(3);
try {
Object obj = method.invoke(o, null);
Object value = mapObject(obj);
map.put(key, value);
finalValue = new JSONObject(map);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return finalValue;
}
public JSONObject CreateNewAccount(String User_Name, String Password) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface", "RestAPI");
o.put("method", "CreateNewAccount");
p.put("User_Name", mapObject(User_Name));
p.put("Password", mapObject(Password));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
This is my another Activity i have created the instance of restApi
public class UserDetailsActivity extends Activity {
TextView tvFisrtName, tvLastName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_details);
// Show the Up button in the action bar.
//setupActionBar();
tvFisrtName=(TextView)findViewById(R.id.tv_firstname);
tvLastName=(TextView)findViewById(R.id.tv_lastname);
Intent i=getIntent();
String username=i.getStringExtra("User_Name");
new AsyncUserDetails().execute(username);
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
//getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
protected class AsyncUserDetails extends AsyncTask<String,Void,JSONObject>
{
String str1;
#Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
JSONObject jsonObj = null;
//here i have error
RestAPI api = new RestAPI();
try {
jsonObj = api.GetUserDetails(params[0]);
//JSONParser parser = new JSONParser();
//userDetail = parser.parseUserDetails(jsonObj);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncUserDetails", e.getMessage());
}
return jsonObj;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
try {
JSONObject jsonObj=result.getJSONArray("Value").getJSONObject(0);
str1=jsonObj.getString("user_id").toString();
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(UserDetailsActivity.this, str1, Toast.LENGTH_SHORT).show();
tvFisrtName.setText(str1);
}
}
public class RestAPI {
String url;
// create constructor here
public RestAPI(String url){
this.url=url;
}
String urlString;
//String data;
public void persistItems(String info) {
Context context = AlertForIp.getContext();
/* SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
data = prefs.getString("stringid", "no id");*/
urlString=info;
}
//private final String urlString = "http://10.0.2.2:1219/Json/Handler.ashx";
private static String convertStreamToUTF8String(InputStream stream) throws IOException {
String result = "";
StringBuilder sb = new StringBuilder();
try {
InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[4096];
int readedChars = 0;
while (readedChars != -1) {
readedChars = reader.read(buffer);
if (readedChars > 0)
sb.append(buffer, 0, readedChars);
}
result = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
private String load(String contents) throws IOException {
//i want to add that urlstring here;
now you can use here url directly
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(60000);
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStreamWriter w = new OutputStreamWriter(conn.getOutputStream());
w.write(contents);
w.flush();
InputStream istream = conn.getInputStream();
String result = convertStreamToUTF8String(istream);
return result;
}
private Object mapObject(Object o) {
Object finalValue = null;
if (o.getClass() == String.class) {
finalValue = o;
} else if (Number.class.isInstance(o)) {
finalValue = String.valueOf(o);
} else if (Date.class.isInstance(o)) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss", new Locale("en", "USA"));
finalValue = sdf.format((Date) o);
} else if (Collection.class.isInstance(o)) {
Collection<?> col = (Collection<?>) o;
JSONArray jarray = new JSONArray();
for (Object item : col) {
jarray.put(mapObject(item));
}
finalValue = jarray;
} else {
Map<String, Object> map = new HashMap<String, Object>();
Method[] methods = o.getClass().getMethods();
for (Method method : methods) {
if (method.getDeclaringClass() == o.getClass()
&& method.getModifiers() == Modifier.PUBLIC
&& method.getName().startsWith("get")) {
String key = method.getName().substring(3);
try {
Object obj = method.invoke(o, null);
Object value = mapObject(obj);
map.put(key, value);
finalValue = new JSONObject(map);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return finalValue;
}
public JSONObject CreateNewAccount(String User_Name, String Password) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface", "RestAPI");
o.put("method", "CreateNewAccount");
p.put("User_Name", mapObject(User_Name));
p.put("Password", mapObject(Password));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
use here
RestAPI rss=new RestAPI(urlString );

Android: white screen while onCreate

I have an app that at launch inside onCreate method copies data from assets folder. It does it in three for cycles, each with activity indicator and the problem is that when first two cycles run white screen shows and only when third loop starts i can seen activity screen with indicator on it.
The code is following
Realm realm;
ListView list;
int[] imageidsm = {R.drawable.fon_sovety350, R.drawable.fon_german350, R.drawable.fon_usa350, R.drawable.fon_uk350, R.drawable.fon_fr_it200, R.drawable.fon_japan_china200, R.drawable.fon_history200};
String[] itemname = {"СССР", "ГЕРМАНИЯ", "США", "ВЕЛИКОБРИТАНИЯ", "ФРАНЦИЯ И ИТАЛИЯ", "ЯПОНИЯ И КИТАЙ", "ИСТОРИЯ"};
Boolean firstLaunch = false;
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int width = metrics.widthPixels;
MainAdapter adapter = new MainAdapter(this, itemname, imageidsm, height, width);
list = (ListView) findViewById(R.id.mainListView);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 2) {
Intent toSssr = new Intent(MainActivity.this, TankListActivity.class);
toSssr.putExtra("category", "СССР");
startActivity(toSssr);
} else if (position == 3) {
Intent listActivity = new Intent(MainActivity.this, ArticleListActivity.class);
startActivity(listActivity);
}
}
});
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this)
.name("db.realm")
.build();
realm.setDefaultConfiguration(realmConfiguration);
realm = Realm.getDefaultInstance();
preferences = getApplicationContext().getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
firstLaunch = preferences.getBoolean("firstLaunch", false);
if (firstLaunch == false) {
firstLaunch();
}
}
public void firstLaunch() {
String[] arrayOfCatLists = {"00f.json", "01f.json", "02f.json", "10f.json"};
String[] arrayOfArticles = {"32.json", "34.json", "44.json", "51.json", "33.json", "40.json", "41.json", "42.json", "52.json", "45.json", "37.json", "46.json", "36.json", "54.json", "35.json", "43.json", "47.json", "50.json", "49.json", "48.json", "56.json", "58.json", "53.json", "59.json" , "55.json", "60.json", "61.json"};
String[] arrayOfUsssr = {"62.json", "74.json", "75.json", "76.json", "63.json", "78.json", "79.json", "77.json", "81.json", "80.json"};
for (int i = 0; i < arrayOfCatLists.length; i++) {
new GetArticlesListFromDisk(arrayOfCatLists[i], i).execute();
}
for (int i = 0; i < arrayOfArticles.length; i++) {
new GetArticleFromDisk(arrayOfArticles[i]).execute();
}
for (int i = 0; i < arrayOfUsssr.length; i++) {
new GetTanksFromDisk(arrayOfUsssr[i]).execute();
}
firstLaunch = true;
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("firstLaunch", firstLaunch);
editor.apply();
}
private class GetArticlesListFromDisk extends AsyncTask<String, Void, String> {
private String id;
private int index;
String[] arrayOfCatLists = {"00f.json", "01f.json", "02f.json"};
private GetArticlesListFromDisk(String id, int index) {
this.id = id;
this.index = index;
}
ProgressDialog pd = new ProgressDialog(MainActivity.this);
#Override
protected String doInBackground(String... params) {
String json = null;
try {
InputStream input = getApplicationContext().getAssets().open(id);
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
json = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd.setCancelable(false);
pd.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
pd.setMessage("Минуточку, загружаемся");
pd.show();
}
#Override
protected void onPostExecute(String strJson) {
super.onPostExecute(strJson);
pd.dismiss();
JSONObject dataJsonObj = null;
String category = "";
try {
dataJsonObj = new JSONObject(strJson);
JSONArray listing = dataJsonObj.getJSONArray("listing");
for (int i = 0; i < listing.length(); i++) {
JSONObject object = listing.getJSONObject(i);
String id = object.getString("id");
String title = object.getString("title");
String subtitle = object.getString("subtitle");
String image = object.getString("image");
InputStream inputStream =null;
Bitmap bitmap = null;
try {
inputStream = getAssets().open(image);
bitmap = BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
Log.d("getArticleFromDisk", "Saved article " + title);
ImageStorage.saveToSdCard(bitmap, image, getApplicationContext());
if (index == 0) {
category = "Танковые сражения";
} else if (index == 1) {
category = "Справочник танкиста";
} else if (index == 2) {
category = "Танковые асы";
} else if (index == 3) {
category = "СССР";
} else if (index == 4) {
category = "Германия";
} else if (index == 5) {
category = "США";
} else if (index == 6) {
category = "Великобритания";
}
realm.beginTransaction();
ArticleList articleList = realm.createObject(ArticleList.class);
articleList.setId(id);
articleList.setTitle(title);
articleList.setSubtitle(subtitle);
articleList.setImage(image);
articleList.setCategory(category);
realm.commitTransaction();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private class GetArticleFromDisk extends AsyncTask<String, Void, String> {
private String id;
private int categoryIndex;
private GetArticleFromDisk(String id) {
this.id = id;
}
public String LOG_TAG = "GetArticleFromDisk";
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String resultJson = "";
ProgressDialog pd = new ProgressDialog(MainActivity.this);
#Override
protected String doInBackground(String... params) {
String json = null;
try {
InputStream input = getApplicationContext().getAssets().open(id);
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
json = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd.setCancelable(false);
pd.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
pd.setMessage("Минуточку, загружаемся");
pd.show();
}
#Override
protected void onPostExecute(String strJson) {
super.onPostExecute(strJson);
pd.dismiss();
JSONObject dataJsonObj = null;
String category = "";
try {
dataJsonObj = new JSONObject(strJson);
JSONArray listing = dataJsonObj.getJSONArray("article");
for (int i = 0; i < listing.length(); i++) {
JSONObject object = listing.getJSONObject(i);
String id = object.getString("id");
String title = object.getString("title");
String subtitle = object.getString("subtitle");
String body = object.getString("body");
String hash = object.getString("content_version");
Log.d(LOG_TAG, "Saved article with id " + id);
realm.beginTransaction();
Article article = realm.createObject(Article.class);
article.setId(id);
article.setTitle(title);
article.setSubtitle(subtitle);
article.setBody(body);
article.setHash(hash);
realm.commitTransaction();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private class GetTanksFromDisk extends AsyncTask<String, Void, Tank> {
private String id;
private int categoryIndex;
private GetTanksFromDisk(String id) {
this.id = id;
}
public String LOG_TAG = "GetTankFromDisk";
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String resultJson = "";
ProgressDialog pd = new ProgressDialog(MainActivity.this);
Tank tank = new Tank();
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.d(LOG_TAG, "Entered preExecute");
pd.setCancelable(false);
pd.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
pd.setMessage("Минуточку, загружаемся");
pd.show();
}
#Override
protected Tank doInBackground(String... params) {
String json = null;
try {
InputStream input = getApplicationContext().getAssets().open(id);
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
json = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
JSONObject dataJsonObj = null;
String category = "";
try {
dataJsonObj = new JSONObject(json);
JSONArray listing = dataJsonObj.getJSONArray("article");
for (int i = 0; i < listing.length(); i++) {
JSONObject object = listing.getJSONObject(i);
String id = object.getString("id");
String title = object.getString("title");
JSONArray signatures = object.getJSONArray("signatures");
ArrayList<String> signatures_list = new ArrayList<String>();
for (int j = 0; j < signatures.length(); j++) {
signatures_list.add(signatures.get(j).toString());
}
String signatures_string = Joiner.on(",").join(signatures_list);
String body = object.getString("body");
String construction = object.getString("construction");
String modification = object.getString("modification");
String ttx = object.getString("ttx");
JSONObject images = object.getJSONObject("images");
JSONArray tank_slider = images.getJSONArray("tank_slider");
ArrayList<String> tank_slider_list = new ArrayList<String>();
for (int k = 0; k < tank_slider.length(); k++) {
InputStream inputStream =null;
Bitmap bitmap = null;
try {
inputStream = getAssets().open(tank_slider.getString(k));
bitmap = BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
ImageStorage.saveToSdCard(bitmap, tank_slider.getString(k), getApplicationContext());
tank_slider_list.add(tank_slider.getString(k));
}
String tank_slider_string = Joiner.on(",").join(tank_slider_list);
String hash = object.getString("content_version");
Log.d(LOG_TAG, "Imported from assets tank with id " + id);
tank.setId(id);
tank.setTitle(title);
tank.setSignatures(signatures_string);
tank.setBody(body);
tank.setConstruction(construction);
tank.setModification(modification);
tank.setTtx(ttx);
tank.setTank_slider(tank_slider_string);
tank.setHash(hash);
}
} catch (JSONException e) {
e.printStackTrace();
}
return tank;
}
#Override
protected void onPostExecute(Tank tank) {
super.onPostExecute(tank);
pd.dismiss();
realm.beginTransaction();
Tank newTank = realm.createObject(Tank.class);
newTank.setId(tank.getId());
newTank.setTitle(tank.getTitle());
newTank.setSignatures(tank.getSignatures());
newTank.setBody(tank.getBody());
newTank.setConstruction(tank.getConstruction());
newTank.setModification(tank.getModification());
newTank.setTtx(tank.getTtx());
newTank.setTank_slider(tank.getTank_slider());
newTank.setHash(tank.getHash());
realm.commitTransaction();
}
}
What Im I doing wrong ?

How to use variables that have been declared in another class in android?

I have two classes of which one extends Activity and the other extends BroadcastReceiver.I have declared a few variables in MainActivity class and need to use this in the IncomingSms class. How do I use the variables. Here is my code.
From the MainActivity class I need to use the variable full_address in my IncomingSms class.
MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy stricMode = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(stricMode);
}
TextView address_textview =(TextView)findViewById(R.id.address);
address_textview.setText(getAddress());
}
public String getAddress() {
String address1 = "";
String address2 = "";
String city = "";
String state = "";
String country = "";
String county = "";
String PIN = "";
String full_address = "";
try {
JSONObject jsonObj = getJSONfromURL("http://maps.googleapis.com/maps/api/geocode/json?latlng=" +"12.9818619" + ","
+ "77.6480391" + "&sensor=true");
String Status = jsonObj.getString("status");
if (Status.equalsIgnoreCase("OK")) {
JSONArray Results = jsonObj.getJSONArray("results");
JSONObject zero = Results.getJSONObject(0);
JSONArray address_components = zero.getJSONArray("address_components");
for (int i = 0; i < address_components.length(); i++) {
JSONObject zero2 = address_components.getJSONObject(i);
String long_name = zero2.getString("long_name");
JSONArray mtypes = zero2.getJSONArray("types");
String Type = mtypes.getString(0);
if (TextUtils.isEmpty(long_name) == false || !long_name.equals(null) || long_name.length() > 0 || long_name != "") {
if (Type.equalsIgnoreCase("street_number")) {
address1 = long_name + " ";
} else if (Type.equalsIgnoreCase("route")) {
address1 = address1 + long_name;
} else if (Type.equalsIgnoreCase("sublocality")) {
address2 = long_name;
} else if (Type.equalsIgnoreCase("locality")) {
// Address2 = Address2 + long_name + ", ";
city = long_name;
} else if (Type.equalsIgnoreCase("administrative_area_level_2")) {
county = long_name;
} else if (Type.equalsIgnoreCase("administrative_area_level_1")) {
state = long_name;
} else if (Type.equalsIgnoreCase("country")) {
country = long_name;
} else if (Type.equalsIgnoreCase("postal_code")) {
PIN = long_name;
}
}
full_address = address1 +","+address2+","+city+","+state+","+country+","+PIN;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return full_address;
}
public static JSONObject getJSONfromURL(String url) {
// initialize
InputStream is = null;
String result = "";
JSONObject jObject = null;
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
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;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObject = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jObject;
}
}
I need to use lat1 and lng1 variables in MainActivity.
IncomingSms.java
public class IncomingSms extends BroadcastReceiver {
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String body = currentMessage.getMessageBody().toString();
Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + body);
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "senderNum: "+ senderNum + ", message: " + body, duration);
toast.show();
StringTokenizer tokenizer = new StringTokenizer(body, ",");
Toast toast1 = Toast.makeText(context, "tokenizer", Toast.LENGTH_SHORT);
toast1.show();
int numberOfTokens = tokenizer.countTokens();
String[] splitArr = new String[numberOfTokens];
splitArr[0] = tokenizer.nextToken();
splitArr[1] = tokenizer.nextToken();
Toast toast2 = Toast.makeText(context, "split", Toast.LENGTH_SHORT);
toast2.show();
Toast toast3 = Toast.makeText(context, splitArr[0], Toast.LENGTH_SHORT);
toast3.show();
Toast toast4 = Toast.makeText(context, splitArr[1], Toast.LENGTH_SHORT);
toast4.show();
String lat=splitArr[0];
String lng=splitArr[1];
double lat1=Double.valueOf(lat);
double lng1=Double.valueOf(lng);
}
use the Intent (you need one to start the other Activity) or a Bundle to pass data through Activities.
Create one new class called Constant.java
public class Const {
public static int A = 0;
public static String selectedImagePath;
}
and then in your classes use it like
public class A extends Activity
{
....
....
Const.A = //whatever;
Const.selectedImagePath = //whatever.;
}
public class B extends Broadcastreceiver
{
Const.A = //whatever;
Const.selectedImagePath = //whatever.;
}
then same you can try in your broadcastreceiver class also.
create a separate class
public class Constants {
static long lat1,long1;
public static long getLat1() {
return lat1;
}
public static void setLat1(long lat1) {
Constants.lat1 = lat1;
}
public static long getLong1() {
return long1;
}
public static void setLong1(long long1) {
Constants.long1 = long1;
}
}
from your Broadcast set this value like Constants.setLat1(lat1), and in your activity get values using Constants.getLong1()

Categories

Resources