Cannot get the value from sharedPrefenced - java

Hey guys again with my question
So as in the title, my apps need data from another activity using sharedPreferenced
So far so good I got the data I store WHEN I click the button but when i tried to get the data on the onCreate it just crashing with this error code:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.test.aplikasirevisi, PID: 28272
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.aplikasirevisi/com.test.aplikasirevisi.Information}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2946)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.test.aplikasirevisi.Information.onCreate(Information.java:33)
at android.app.Activity.performCreate(Activity.java:7224)
at android.app.Activity.performCreate(Activity.java:7213)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2926)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:201) 
at android.app.ActivityThread.main(ActivityThread.java:6810) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873) 
I/Process: Sending signal. PID: 28272 SIG: 9
It says it's null but when I click the button it's giving me the data though
Here is my code:
Information.Java
package com.test.aplikasirevisi;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.Nullable;
public class Information extends Activity {
SharedPreferences sharedpreferences;
TextView name;
TextView phonenum;
TextView highest;
TextView lowest;
public static final String mypreference = "mypref";
public static final String Name = "nameKey";
public static final String PhoneNum = "phonenumKey";
public static final String Highest = "highestKey";
public static final String Lowest = "lowestKey";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.information);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(PhoneNum)) {
phonenum.setText(sharedpreferences.getString(PhoneNum, ""));
}
if (sharedpreferences.contains(Highest)) {
highest.setText(sharedpreferences.getString(Highest, ""));
}
if (sharedpreferences.contains(Lowest)) {
lowest.setText(sharedpreferences.getString(Lowest, ""));
}
}
public void Save(View view) {
String n = name.getText().toString();
String p = phonenum.getText().toString();
String h = highest.getText().toString();
String l = lowest.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(PhoneNum, p);
editor.putString(Highest, h);
editor.putString(Lowest, l);
editor.commit();
}
public void clear(View view) {
name = (TextView) findViewById(R.id.etName);
phonenum = (TextView) findViewById(R.id.etPhoneNum);
highest = (TextView) findViewById(R.id.etHighest);
lowest = (TextView) findViewById(R.id.etLowest);
name.setText("");
phonenum.setText("");
highest.setText("");
lowest.setText("");
}
public void Get(View view) {
name = (TextView) findViewById(R.id.etName);
phonenum = (TextView) findViewById(R.id.etPhoneNum);
highest = (TextView) findViewById(R.id.etHighest);
lowest = (TextView) findViewById(R.id.etLowest);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(PhoneNum)) {
phonenum.setText(sharedpreferences.getString(PhoneNum, ""));
}
if (sharedpreferences.contains(Highest)) {
highest.setText(sharedpreferences.getString(Highest, ""));
}
if (sharedpreferences.contains(Lowest)) {
lowest.setText(sharedpreferences.getString(Lowest, ""));
}
}
}
MonitoringScreen.Java
package com.test.aplikasirevisi;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import static com.test.aplikasirevisi.Information.Highest;
import static com.test.aplikasirevisi.Information.Lowest;
import static com.test.aplikasirevisi.Information.mypreference;
public class MonitoringScreen extends Activity {
private static final String TAG = "BlueTest5-MainActivity";
private int mMaxChars = 50000;//Default
private UUID mDeviceUUID;
private BluetoothSocket mBTSocket;
private ReadInput mReadThread = null;
TextView highest;
TextView lowest;
private boolean mIsUserInitiatedDisconnect = false;
private TextView mTxtReceive;
private Button mBtnClearInput;
private Button mBtnGetBPM;
private ScrollView scrollView;
private CheckBox chkScroll;
private CheckBox chkReceiveText;
private boolean mIsBluetoothConnected = false;
private BluetoothDevice mDevice;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_monitoring_screen);
ActivityHelper.initialize(this);
Intent intent = getIntent();
Bundle b = intent.getExtras();
mDevice = b.getParcelable(MainActivity.DEVICE_EXTRA);
mDeviceUUID = UUID.fromString(b.getString(MainActivity.DEVICE_UUID));
mMaxChars = b.getInt(MainActivity.BUFFER_SIZE);
Log.d(TAG, "Ready");
mTxtReceive = (TextView) findViewById(R.id.txtReceive);
chkScroll = (CheckBox) findViewById(R.id.chkScroll);
chkReceiveText = (CheckBox) findViewById(R.id.chkReceiveText);
scrollView = (ScrollView) findViewById(R.id.viewScroll);
mBtnClearInput = (Button) findViewById(R.id.btnClearInput);
mBtnGetBPM = (Button) findViewById(R.id.mBtnGetBPM);
mTxtReceive.setMovementMethod(new ScrollingMovementMethod());
mBtnClearInput.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
mTxtReceive.setText("");
}
});
mBtnGetBPM.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
highest = (TextView) findViewById(R.id.etHighest);
lowest = (TextView) findViewById(R.id.etLowest);
SharedPreferences sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Highest)) {
highest.setText(sharedpreferences.getString(Highest, ""));
}
if (sharedpreferences.contains(Lowest)) {
lowest.setText(sharedpreferences.getString(Lowest, ""));
}
}
});
}
private class ReadInput implements Runnable{
private boolean bStop = false;
private Thread t;
public ReadInput() {
t = new Thread(this, "Input Thread");
t.start();
}
public boolean isRunning() {
return t.isAlive();
}
#Override
public void run() {
InputStream inputStream;
try {
inputStream = mBTSocket.getInputStream();
while (!bStop) {
byte[] buffer = new byte[256];
if (inputStream.available() > 0) {
inputStream.read(buffer);
int i;
/*
* This is needed because new String(buffer) is taking the entire buffer i.e. 256 chars on Android 2.3.4 http://stackoverflow.com/a/8843462/1287554
*/
for (i = 0; i < buffer.length && buffer[i] != 0; i++) {
}
final String strInput = new String(buffer, 0, i);
String getHi = null;
SharedPreferences sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Highest)) {
highest.setText(sharedpreferences.getString(Highest, ""));
getHi=highest.getText().toString();
}
if (sharedpreferences.contains(Lowest)) {
lowest.setText(sharedpreferences.getString(Lowest, ""));
}
int hi = Integer.parseInt(getHi);
/*
* If checked then receive text, better design would probably be to stop thread if unchecked and free resources, but this is a quick fix
*/
if (chkReceiveText.isChecked()) {
mTxtReceive.post(new Runnable() {
#Override
public void run() {
int data = Integer.parseInt(strInput);
mTxtReceive.append(strInput);
int txtLength = mTxtReceive.getEditableText().length();
if(txtLength > mMaxChars){
mTxtReceive.getEditableText().delete(0, txtLength - mMaxChars);
Log.d(TAG, "text longer than allowed:" + mTxtReceive.getEditableText().delete(0, txtLength - mMaxChars));
Log.d(TAG, strInput);
if(data > hi){
Log.d(TAG, "Success");
}
}
if (chkScroll.isChecked()) { // Scroll only if this is checked
scrollView.post(new Runnable() { // Snippet from http://stackoverflow.com/a/4612082/1287554
#Override
public void run() {
scrollView.fullScroll(View.FOCUS_DOWN);
}
});
}
}
});
}
}
Thread.sleep(500);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void stop() {
bStop = true;
}
}
private class DisConnectBT extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
if (mReadThread != null) {
mReadThread.stop();
while (mReadThread.isRunning())
; // Wait until it stops
mReadThread = null;
}
try {
mBTSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mIsBluetoothConnected = false;
if (mIsUserInitiatedDisconnect) {
finish();
}
}
}
private void msg(String s) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
if (mBTSocket != null && mIsBluetoothConnected) {
new DisConnectBT().execute();
}
Log.d(TAG, "Paused");
super.onPause();
}
#Override
protected void onResume() {
if (mBTSocket == null || !mIsBluetoothConnected) {
new ConnectBT().execute();
}
Log.d(TAG, "Resumed");
super.onResume();
}
#Override
protected void onStop() {
Log.d(TAG, "Stopped");
super.onStop();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
private class ConnectBT extends AsyncTask<Void, Void, Void> {
private boolean mConnectSuccessful = true;
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MonitoringScreen.this, "Hold on", "Connecting");// http://stackoverflow.com/a/11130220/1287554
}
#Override
protected Void doInBackground(Void... devices) {
try {
if (mBTSocket == null || !mIsBluetoothConnected) {
mBTSocket = mDevice.createInsecureRfcommSocketToServiceRecord(mDeviceUUID);
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
mBTSocket.connect();
}
} catch (IOException e) {
// Unable to connect to device
e.printStackTrace();
mConnectSuccessful = false;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (!mConnectSuccessful) {
Toast.makeText(getApplicationContext(), "Could not connect to device. Is it a Serial device? Also check if the UUID is correct in the settings", Toast.LENGTH_LONG).show();
finish();
} else {
msg("Connected to device");
mIsBluetoothConnected = true;
mReadThread = new ReadInput(); // Kick off input reader
}
progressDialog.dismiss();
}
}
}
As you can see I tried to automatically get the Highest bpm dan Lowest bpm but it spans the same error so I'm in a pickle now so if anyone can help with it dan fast I'll be grateful for that. And sorry for my English it's not my first language so I can't express it really well.

The TextView in your Information.Java are not assigned to anything within your onCreate method before you try calling the setText method. This is what the error is complaining about.
Your assignments are in the clear(View view) method for some reason.... they should be in the onCreate method.
i.e move
name = (TextView) findViewById(R.id.etName);
phonenum = (TextView) findViewById(R.id.etPhoneNum);
highest = (TextView) findViewById(R.id.etHighest);
lowest = (TextView) findViewById(R.id.etLowest);
out of the clear and get methods and into the onCreate method like:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.information);
name = (TextView) findViewById(R.id.etName);
phonenum = (TextView) findViewById(R.id.etPhoneNum);
highest = (TextView) findViewById(R.id.etHighest);
lowest = (TextView) findViewById(R.id.etLowest);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(PhoneNum)) {
phonenum.setText(sharedpreferences.getString(PhoneNum, ""));
}
if (sharedpreferences.contains(Highest)) {
highest.setText(sharedpreferences.getString(Highest, ""));
}
if (sharedpreferences.contains(Lowest)) {
lowest.setText(sharedpreferences.getString(Lowest, ""));
}
}

Related

Error java.lang.NumberFormatException: Invalid double: "86,24" [duplicate]

This question already has answers here:
Best way to parseDouble with comma as decimal separator?
(10 answers)
Android NumberFormatException: Invalid Double - except the value is a valid Double
(2 answers)
Closed 6 years ago.
Android studio noti this error.This code by a main screen of quiz game
How to fix it??? i was try some guide but nothing
This is My error
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NumberFormatException: Invalid double: "86,24"
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.parseDouble(StringToReal.java:269)
at java.lang.Double.parseDouble(Double.java:295)
at gt.scratchgame.MainActivity.checkAns(MainActivity.java:345)
at gt.scratchgame.MainActivity.onClick(MainActivity.java:318)
at android.view.View.performClick(View.java:4084)
at android.view.View$PerformClick.run(View.java:16966)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
My activity
package gt.scratchgame;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.startapp.android.publish.StartAppAd;
import com.startapp.android.publish.StartAppSDK;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import gt.scratchgame.base.Session;
import gt.scratchgame.bean.AnsOptionBean;
import gt.scratchgame.bean.BeanEachQuetionScore;
import gt.scratchgame.bean.QuestionAnsbean;
import gt.scratchgame.constants.AppConstants;
import gt.scratchgame.database.DBhelper;
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private WScratchView scratchView;
private TextView percentageView, scorelabel, textViewNo, textViewcounter, textViewTotalScore, textView3;
private float mPercentage;
public DBhelper dbhelper;
AQuery aQuery;
private static QuestionAnsbean questionAnsbean1;
private static String trueAns = null;
private static int quetionNumber = 0;
protected Button gameActivityButton1, gameActivityButton2, gameActivityButton3, gameActivityButton4;
ImageView imageView;
Session session;
Bitmap bitmap;
Typeface typeface;
private static float totalScore = 0;
public List<QuestionAnsbean> questionAnsList;
private List<BeanEachQuetionScore> scoreList;
ProgressDialog dialog;
private StartAppAd startAppAd;
AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
}
#Override
protected void onResume() {
super.onResume();
questionAnsList = new ArrayList<QuestionAnsbean>();
startAppAd = new StartAppAd(this);
aQuery = new AQuery(this);
session = Session.getInstance();
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.scratchview1);
scoreList = new ArrayList<BeanEachQuetionScore>();
scratchView = (WScratchView) findViewById(R.id.scratch_view);
scratchView.setScratchBitmap(bitmap);
typeface = Typeface.createFromAsset(getAssets(),"customestyle.TTF");
totalScore = 0;
quetionNumber = 0;
dialog = new ProgressDialog(this);
initDialogProperty();
asyncJson();
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
StartAppSDK.init(this, AppConstants.DEVELOPER_ID, AppConstants.APP_ID, true);
// StartAppAd.showSlider(this);
startAppAd.showAd();
}
private void initDialogProperty() {
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setIndeterminate(false);
dialog.setCancelable(false);
dialog.setMessage("Loading...");
}
private void initUI() {
percentageView = (TextView) findViewById(R.id.percentage);
percentageView.setTypeface(typeface);
scorelabel = (TextView) findViewById(R.id.scorelabel);
scorelabel.setTypeface(typeface);
textViewNo = (TextView) findViewById(R.id.textViewNo);
textViewNo.setTypeface(typeface);
textViewcounter = (TextView) findViewById(R.id.textViewcounter);
textViewcounter.setTypeface(typeface);
textViewTotalScore = (TextView) findViewById(R.id.textViewTotalScore);
textViewTotalScore.setTypeface(typeface);
textViewTotalScore.setText(totalScore + "");
textView3 = (TextView) findViewById(R.id.textView3);
textView3.setTypeface(typeface);
dbhelper = DBhelper.getInstance(getApplicationContext());
dbhelper.open();
initDb();
Collections.shuffle(questionAnsList);
/*Game Activity 4 option button*/
gameActivityButton1 = (Button) findViewById(R.id.gameActivityButton1);
gameActivityButton2 = (Button) findViewById(R.id.gameActivityButton2);
gameActivityButton3 = (Button) findViewById(R.id.gameActivityButton3);
gameActivityButton4 = (Button) findViewById(R.id.gameActivityButton4);
gameActivityButton1.setTypeface(typeface);
gameActivityButton2.setTypeface(typeface);
gameActivityButton3.setTypeface(typeface);
gameActivityButton4.setTypeface(typeface);
gameActivityButton1.setOnClickListener(this);
gameActivityButton2.setOnClickListener(this);
gameActivityButton3.setOnClickListener(this);
gameActivityButton4.setOnClickListener(this);
quetionInitialize();
// customize attribute programmatically
scratchView.setScratchable(true);
scratchView.setRevealSize(50);
scratchView.setAntiAlias(true);
// scratchView.setOverlayColor(Color.RED);
scratchView.setBackgroundClickable(true);
// add callback for update scratch percentage
scratchView.setOnScratchCallback(new WScratchView.OnScratchCallback() {
#Override
public void onScratch(float percentage) {
updatePercentage(percentage);
}
#Override
public void onDetach(boolean fingerDetach) {
/* if(mPercentage > 1){
scratchView.setScratchAll(true);
updatePercentage(100);
}*/
}
});
updatePercentage(0f);
}
private void updatePercentage(float percentage) {
mPercentage = percentage;
String percentage2decimal = String.format("%.2f", (100 - percentage));
percentageView.setText(percentage2decimal);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
/* #Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}*/
private void initDb() {
// Toast.makeText(getApplicationContext()," DB size-- "+dbhelper.getUserData().size(),Toast.LENGTH_LONG).show();
// dbhelper.addData(session.getSelectedCategory().id,"guru",123.36f);
}
public void asyncJson() {
// String url = "http://gurutechnolabs.com/demo/kids/demo.php?category=+""&level=level";
// Toast.makeText(getApplicationContext(),"aaaaaa",Toast.LENGTH_LONG).show();
int id = session.getSelectedCategory().id;
dialog.show();
String url = "http://8chan.biz/app/demo.php?category="+id;
Log.d("*************",url);
aQuery.ajax(url, JSONObject.class, new AjaxCallback<JSONObject>() {
#Override
public void callback(String url, JSONObject json, AjaxStatus status) {
if (json != null) {
try {
JSONObject mainJsonObject = new JSONObject(json.toString());
if(mainJsonObject != null)
{
JSONArray list = mainJsonObject.getJSONArray("data");
if(list != null)
{
for(int i = 0 ; i < list.length() ; i++)
{
JSONObject subObject = list.getJSONObject(i);
// aQuery.id(R.id.result).visible().text(subObject.toString());
QuestionAnsbean questionAnsbean = new QuestionAnsbean();
questionAnsbean.id = subObject.getInt("id");
questionAnsbean.cat_id = subObject.getInt("cat_id");
questionAnsbean.url = subObject.getString("url");
JSONArray questionAnsOptionArrary = subObject.getJSONArray("answers");
for (int j = 0; j < questionAnsOptionArrary.length(); j++)
{
JSONObject suObject1 = questionAnsOptionArrary.getJSONObject(j);
AnsOptionBean ansOptionBean = new AnsOptionBean();
ansOptionBean.answer = suObject1.getString("answer");
ansOptionBean.result = suObject1.getInt("result");
questionAnsbean.ansOptionList.add(ansOptionBean);
}
questionAnsList.add(questionAnsbean);
// session.setOperationLists1(questionAnsbean);
// Toast.makeText(getApplicationContext(),levelLists.size()+"",Toast.LENGTH_LONG).show();
//gameLevelGridAdapter.notifyDataSetChanged();
}
// Collections.shuffle(ansOptionList);
}
// Toast.makeText(getApplicationContext(),questionAnsList.size()+" This is list size in asin aquery ",Toast.LENGTH_LONG).show();
initUI();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Toast.makeText(getApplicationContext(), listItem.size()+"", Toast.LENGTH_LONG).show();
//showResult(json, status);
} else {
// ajax error, show error code
/* Toast.makeText(aQuery.getContext(),
"Error:" + status.getMessage(), Toast.LENGTH_LONG)
.show();*/
}
}
});
}
private void quetionInitialize() {
scratchView.resetView();
scratchView.setScratchAll(false);
textViewcounter.setText(quetionNumber+"");
questionAnsbean1 = new QuestionAnsbean();
questionAnsbean1 = questionAnsList.get(quetionNumber);
dialog.dismiss();
aQuery.id(R.id.extra).progress(dialog).image(questionAnsList.get(quetionNumber).url, true, true);
ansOptionInitialize();
}
/*Quation ans intialize and set*/
private void ansOptionInitialize() {
try {
Collections.shuffle(questionAnsbean1.ansOptionList);
gameActivityButton1.setText(questionAnsbean1.ansOptionList.get(0).answer);
gameActivityButton2.setText(questionAnsbean1.ansOptionList.get(1).answer);
gameActivityButton3.setText(questionAnsbean1.ansOptionList.get(2).answer);
gameActivityButton4.setText(questionAnsbean1.ansOptionList.get(3).answer);
if(questionAnsbean1.ansOptionList.get(0).result == 1)
{
trueAns = questionAnsbean1.ansOptionList.get(0).answer;
}
else if(questionAnsbean1.ansOptionList.get(1).result == 1)
{
trueAns = questionAnsbean1.ansOptionList.get(1).answer;
}
else if(questionAnsbean1.ansOptionList.get(2).result == 1)
{
trueAns = questionAnsbean1.ansOptionList.get(2).answer;
}
else if(questionAnsbean1.ansOptionList.get(3).result == 1)
{
trueAns = questionAnsbean1.ansOptionList.get(3).answer;
}
}
catch (Exception e)
{
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.gameActivityButton1:
checkAns(gameActivityButton1.getText().toString());
break;
case R.id.gameActivityButton2:
checkAns(gameActivityButton2.getText().toString());
break;
case R.id.gameActivityButton3:
checkAns(gameActivityButton3.getText().toString());
break;
case R.id.gameActivityButton4:
checkAns(gameActivityButton4.getText().toString());
break;
default:
break;
}
}
private void checkAns(String text) {
BeanEachQuetionScore beanEachQuetionScore = new BeanEachQuetionScore();
beanEachQuetionScore.quetionNo = quetionNumber;
beanEachQuetionScore.url = questionAnsList.get(quetionNumber).url;
beanEachQuetionScore.playerAns = text;
beanEachQuetionScore.trueAns = trueAns;
beanEachQuetionScore.quetionScore = Double.parseDouble(percentageView.getText().toString());
scoreList.add(beanEachQuetionScore);
if (text.equals(trueAns)) {
totalScore = totalScore + Float.parseFloat(percentageView.getText().toString());
textViewTotalScore.setText(String.format("%.2f", totalScore));
quetionNumber++;
if(quetionNumber < questionAnsList.size()) {
quetionInitialize();
}
else {
gameOver();
}
}
else {
totalScore = totalScore - Float.parseFloat(percentageView.getText().toString());
textViewTotalScore.setText(String.format("%.2f", totalScore));
quetionNumber++;
if(quetionNumber < questionAnsList.size()) {
quetionInitialize();
}
else {
gameOver();
}
}
}
private void gameOver() {
session.setScoreBeen(scoreList);
session.setTotalScoreInSession(Float.parseFloat(textViewTotalScore.getText().toString()));
Intent intent = new Intent(getApplicationContext(),ScoreBord.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(getApplicationContext(),SelectCategoryActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
Your issue actually brings up a larger issue that is especially relevant when developing a mobile app: Locale. Rather than use Double.parse(), which does not take Locale into account, consider using NumberFormat instead.
NumberFormat nf = NumberFormat.getInstance(); //gets an instance with the default Locale
Number parsed = nf.parse(percentageView.getText().toString());
beanEachQuetionScore.quetionScore = parsed.doubleValue();
For your float values, you can use the same concept:
Number parsedFloat = nf.parse(someFloatString);
float floatVal = parsedFloat.floatValue();
This of course assumes that OP is in a Locale that uses ',' instead of '.' as a separator.

error return NULL app json_code return NULL

I have a android application news, where I receive data from a server Jons until everything well, the problem is that when I'm in the app and minimize to do something else and when I try to resume where I left off the app comes with NULL data
part
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class ActivityDetailStory extends AppCompatActivity {
int position;
String str_cid, str_cat_id, str_cat_image, str_cat_name, str_title, str_image, str_desc, str_date;
TextView news_title, news_date;
WebView news_desc;
ImageView img_news, img_fav;
DatabaseHandler db;
List<ItemStoryList> arrayOfRingcatItem;
ItemStoryList objAllBean;
final Context context = this;
ProgressBar progressBar;
LinearLayout content;
private AdView mAdView;
private InterstitialAd interstitial;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_story);
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final android.support.v7.app.ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(Constant.CATEGORY_TITLE);
}
//show admob banner ad
mAdView = (AdView) findViewById(R.id.adView);
mAdView.loadAd(new AdRequest.Builder().build());
mAdView.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
}
#Override
public void onAdFailedToLoad(int error) {
mAdView.setVisibility(View.GONE);
}
#Override
public void onAdLeftApplication() {
}
#Override
public void onAdOpened() {
}
#Override
public void onAdLoaded() {
mAdView.setVisibility(View.VISIBLE);
}
});
content = (LinearLayout) findViewById(R.id.content);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
img_fav = (FloatingActionButton) findViewById(R.id.img_fav);
img_news = (ImageView) findViewById(R.id.image);
news_title = (TextView) findViewById(R.id.title);
news_date = (TextView) findViewById(R.id.subtitle);
news_desc = (WebView) findViewById(R.id.desc);
db = new DatabaseHandler(ActivityDetailStory.this);
arrayOfRingcatItem = new ArrayList<ItemStoryList>();
//imageLoader = new ImageLoader(ActivityDetailStory.this);
if (JsonUtils.isNetworkAvailable(ActivityDetailStory.this)) {
new MyTask().execute(Constant.SERVER_URL + "/api.php?nid=" + Constant.NEWS_ITEMID);
MyApplication.getInstance().trackScreenView("Lendo de cara : " + (Constant.CATEGORY_TITLE));
}
else {
Toast.makeText(getApplicationContext(), "Problema com sua Rede de Internet", Toast.LENGTH_SHORT).show();
}
}
private class MyTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... params) {
return JsonUtils.getJSONString(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressBar.setVisibility(View.GONE);
content.setVisibility(View.VISIBLE);
if (null == result || result.length() == 0) {
Toast.makeText(getApplicationContext(), "Problema com sua Rede de Internet!", Toast.LENGTH_SHORT).show();
} else {
try {
JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray = mainJson.getJSONArray(Constant.CATEGORY_ARRAY_NAME);
JSONObject objJson = null;
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
ItemStoryList objItem = new ItemStoryList();
objItem.setCId(objJson.getString(Constant.CATEGORY_ITEM_CID));
objItem.setCategoryName(objJson.getString(Constant.CATEGORY_ITEM_NAME));
objItem.setCategoryImage(objJson.getString(Constant.CATEGORY_ITEM_IMAGE));
objItem.setCatId(objJson.getString(Constant.CATEGORY_ITEM_CAT_ID));
objItem.setNewsImage(objJson.getString(Constant.CATEGORY_ITEM_NEWSIMAGE));
objItem.setNewsHeading(objJson.getString(Constant.CATEGORY_ITEM_NEWSHEADING));
objItem.setNewsDescription(objJson.getString(Constant.CATEGORY_ITEM_NEWSDESCRI));
objItem.setNewsDate(objJson.getString(Constant.CATEGORY_ITEM_NEWSDATE));
arrayOfRingcatItem.add(objItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
setAdapterToListview();
}
}
}
public void setAdapterToListview() {
objAllBean = arrayOfRingcatItem.get(0);
str_cid = objAllBean.getCId();
str_cat_name = objAllBean.getCategoryName();
str_cat_image = objAllBean.getCategoryImage();
str_cat_id = objAllBean.getCatId();
str_title = objAllBean.getNewsHeading();
str_desc = objAllBean.getNewsDescription();
str_image = objAllBean.getNewsImage();
str_date = objAllBean.getNewsDate();
news_title.setText(str_title);
news_date.setText(str_date);
news_desc.setBackgroundColor(Color.parseColor("#FFFFFF"));
news_desc.setFocusableInTouchMode(false);
news_desc.setFocusable(false);
news_desc.getSettings().setDefaultTextEncodingName("UTF-8");
WebSettings webSettings = news_desc.getSettings();
Resources res = getResources();
int fontSize = res.getInteger(R.integer.font_size);
webSettings.setDefaultFontSize(fontSize);
String mimeType = "text/html; charset=UTF-8";
String encoding = "utf-8";
String htmlText = str_desc;
String text = "<html><head><style type=\"text/css\">#font-face {font-family: MyFont;src: url(\"file:///android_asset/Roboto-Light.ttf\")}body {font-family: MyFont;font-size: medium; color: #525252;}</style></head><body>"
+ htmlText + "</body></html>";
news_desc.loadData(text, mimeType, encoding);
List<Pojo> pojolist = db.getFavRow(str_cat_id);
if (pojolist.size() == 0) {
img_fav.setImageResource(R.drawable.ic_bookmark_outline);
} else {
if (pojolist.get(0).getCatId().equals(str_cat_id))
;
{
img_fav.setImageResource(R.drawable.ic_bookmark_white);
}
}
img_fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
List<Pojo> pojolist = db.getFavRow(str_cat_id);
if (pojolist.size() == 0) {
db.AddtoFavorite(new Pojo(str_cat_id, str_cid, str_cat_name, str_title, str_image, str_desc, str_date));
Toast.makeText(getApplicationContext(), "Leitura Marcada", Toast.LENGTH_SHORT).show();
img_fav.setImageResource(R.drawable.ic_bookmark_white);
interstitial = new InterstitialAd(ActivityDetailStory.this);
interstitial.setAdUnitId(getString(R.string.admob_interstitial_id));
AdRequest adRequest = new AdRequest.Builder().build();
interstitial.loadAd(adRequest);
interstitial.setAdListener(new AdListener() {
public void onAdLoaded() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
});
} else {
if (pojolist.get(0).getCatId().equals(str_cat_id)) {
db.RemoveFav(new Pojo(str_cat_id));
Toast.makeText(getApplicationContext(), "Leitura desmarcada!", Toast.LENGTH_SHORT).show();
img_fav.setImageResource(R.drawable.ic_bookmark_outline);
}
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_story, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
case R.id.menu_share:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Estou lendo vários livro com esse app estou adorando, baixe já, Recomendo "+"https://play.google.com/store/apps/details?id="+getPackageName());
sendIntent.setType("text/plain");
startActivity(sendIntent);
break;
default:
return super.onOptionsItemSelected(menuItem);
}
return true;
}
#Override
protected void onPause() {
// mAdView.pause();
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
//mAdView.resume();
}
#Override
protected void onDestroy() {
//mAdView.destroy();
super.onDestroy();
}
}
what you get in the log is, the more I believe that it has nothing to do.
03-21 18:58:20.032 1342-1342/? E/dalvikvm: Could not find class 'android.app.AppOpsManager', referenced from method com.google.android.gms.common.ou.a
03-21 18:58:20.165 1342-1342/? E/dalvikvm: Could not find class 'android.app.AppOpsManager', referenced from method com.google.android.gms.common.j.a
03-21 18:58:20.404 1342-1342/? E/com.parse.PushService: The Parse push service cannot start because Parse.initialize has not yet been called. If you call Parse.initialize from an Activity's onCreate, that call should instead be in the Application.onCreate. Be sure your Application class is registered in your AndroidManifest.xml with the android:name property of your <application> tag.
03-21 18:58:20.604 1416-1416/? E/dalvikvm: Could not find class 'android.app.AppOpsManager', referenced from method com.google.android.gms.common.GooglePlayServicesUtil.zza
03-21 18:58:20.777 1284-1445/? E/sqlite3_android: CDF_MAX_DIGIT_MATCH = 100
03-21 18:58:20.777 1284-1445/? E/sqlite3_android: CDF_MIN_DIGIT_MATCH = 7
03-21 18:58:21.014 1416-1478/? E/sqlite3_android: CDF_MAX_DIGIT_MATCH = 100
03-21 18:58:21.014 1416-1478/? E/sqlite3_android: CDF_MIN_DIGIT_MATCH = 7
How do I not return NULL
Thank you

In AsyncTask, stop making registerReceiver() freeze the app

Since I finally figured out that the registerReceiver() method is usually running on the UI-Thread, I now want to change that. I just need some advice of how I could do that.
How would I be able to change registerReceiver() to stop freezing my app?
My doInBackground() method from the AsyncTask, runs another method that is using the registerReceiver(mReceiver, filter) method (both variables are already defined). But I want to keep seeing my ProgressDialog instead of making the app freezing.
I read about using a Handler and a new Thread, but I need some help there.
Thanks in advance.
Code:
package ch.scs.mod.tools.messagegenerator.business;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.telephony.SmsManager;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import ch.scs.mod.tools.messagegenerator.R;
import ch.scs.mod.tools.messagegenerator.model.Testcase;
import ch.scs.mod.tools.messagegenerator.model.Testset;
public class ReportActivity extends Activity implements OnClickListener {
private static final String TAG = "ReportActivity";
private TextView title;
private TextView lblReport;
private TextView lblEmail;
private TableLayout tblReport;
private Button btnBack;
private Testset testset;
private Testcase testcase;
private List<Testcase> testcases = new ArrayList<Testcase>();
private String number;
private String apn = "not used";
private String error;
private ArrayList<String> resultarray = new ArrayList<String>();
private ProgressDialog progressdialog;
private boolean running = false;
public enum State {
UNKNOWN, CONNECTED, NOT_CONNECTED
}
private ConnectivityManager mConnMgr;
private PowerManager.WakeLock mWakeLock;
private ConnectivityBroadcastReceiver mReceiver;
private NetworkInfo mNetworkInfo;
private State mState;
private boolean mListening;
private boolean mSending;
private SendMms sendMms = SendMms.getInstance();
private MMSTest myTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.report);
title = (TextView) findViewById(R.id.lblTitle);
lblReport = (TextView) findViewById(R.id.lblReport);
lblEmail = (TextView) findViewById(R.id.lblMmsEmail);
tblReport = (TableLayout) findViewById(R.id.tblReport);
btnBack = (Button) findViewById(R.id.btnBack);
progressdialog = new ProgressDialog(this);
progressdialog.setTitle("Please wait...");
progressdialog.setMessage("Sending...");
progressdialog.setCancelable(false);
Typeface tf = Typeface.createFromAsset(getAssets(),
"fonts/TheSansB_TT4_App.ttf");
title.setTypeface(tf);
lblEmail.setTypeface(tf);
lblReport.setTypeface(tf);
btnBack.setTypeface(tf);
lblEmail.setText(Html
.fromHtml("<a href=\'mailto:mathias.hubacher#swisscom.com\'>mathias.hubacher#swisscom.com</a>"));
lblEmail.setMovementMethod(LinkMovementMethod.getInstance());
btnBack.setOnClickListener(this);
testset = (Testset) this.getIntent().getSerializableExtra("testset");
number = (String) this.getIntent().getStringExtra("number");
lblReport.setText(getResources().getString(R.string.reportText1) + " "
+ number + " " + getResources().getString(R.string.reportText2));
testcases = testset.getTestcases();
resultarray.clear();
// Creating Views for Asynctask
ScrollView sv = new ScrollView(this);
LinearLayout ll = new LinearLayout(this);
HorizontalScrollView hsv = new HorizontalScrollView(this);
sv.setLayoutParams(new ScrollView.LayoutParams(ScrollView.LayoutParams.MATCH_PARENT, getWindowManager().getDefaultDisplay().getHeight()/2));
sv.setVerticalScrollBarEnabled(true);
sv.setHorizontalScrollBarEnabled(true);
sv.setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET);
hsv.setLayoutParams(new HorizontalScrollView.LayoutParams(HorizontalScrollView.LayoutParams.MATCH_PARENT, HorizontalScrollView.LayoutParams.MATCH_PARENT));
hsv.setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET);
ll.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
ll.setOrientation(LinearLayout.VERTICAL);
for (Testcase testc : testcases) {
TableRow tr = new TableRow(this);
TextView tv = new TextView(this);
TextView tvok = new TextView(this);
TextView tverror = new TextView(this);
tr.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
tv.setText(testc.getName() + " ");
tv.setTextColor(getResources().getColor(R.color.white));
tr.addView(tv);
tvok.setText("Sending...");
tvok.setTextColor(getResources().getColor(R.color.white));
tverror.setText("");
tverror.setTextColor(getResources().getColor(R.color.orange));
tr.addView(tvok);
tr.addView(tverror);
ll.addView(tr);
testc.setTextView(tv);
testc.setTextViewOk(tvok);
testc.setTextViewError(tverror);
}
hsv.addView(ll);
sv.addView(hsv);
tblReport.addView(sv);
myTask = new MMSTest();
myTask.execute();
}
private void createSms(List<Testcase> tcs) {
for (Testcase testc : tcs) {
error = "";
if (!testc.isExecute()) {
resultarray.add(getResources().getString(R.string.notExe));
resultarray.add(error);
} else {
sendSms(number, testc);
if (testc.isSuccsess()) {
resultarray.add(getResources().getString(R.string.ok));
resultarray.add(error);
} else {
resultarray.add(getResources().getString(R.string.failed));
resultarray.add(error);
}
}
testc.setRunning(true);
myTask.onProgressUpdate(resultarray.get(resultarray.size()-2), resultarray.get(resultarray.size()-1));
}
}
private class MMSTest extends AsyncTask<String, String, ArrayList<String>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mReceiver = new ConnectivityBroadcastReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mReceiver, filter);
// progressdialog.show();
}
#Override
protected ArrayList<String> doInBackground(String... params) {
if (testset.getType().equals("sms")) {
Log.v(TAG, "Testtype SMS");
createSms(testcases);
} else if (testset.getType().equals("mms")) {
Log.v(TAG, "Testtype MMS");
mListening = true;
mSending = false;
mConnMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// mReceiver = new ConnectivityBroadcastReceiver();
apn = (String) ReportActivity.this.getIntent().getStringExtra("apn");
startMms();
} else {
lblReport.setText("Error Testset Type not valid");
}
return resultarray;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
for (Testcase testc : testcases) {
if (testc.getRunning()) {
TextView tvok = testc.getTextViewOk();
TextView tverror = testc.getTextViewError();
if (testc.isExecute()) {
if (testc.isSuccsess()) {
tvok.setText(values[0]);
tvok.setTextColor(getResources().getColor(R.color.green));
tverror.setText(values[1]);
tverror.setTextColor(getResources().getColor(R.color.orange));
}
else {
tvok.setText(values[0]);
tvok.setTextColor(getResources().getColor(R.color.red));
tverror.setText(values[1]);
tverror.setTextColor(getResources().getColor(R.color.white));
}
}
else {
tvok.setText(values[0]);
tvok.setTextColor(getResources().getColor(R.color.red));
tverror.setText(values[1]);
tverror.setTextColor(getResources().getColor(R.color.white));
}
testc.setRunning(false);
break;
}
}
}
#Override
protected void onPostExecute(ArrayList<String> result) {
super.onPostExecute(result);
// int r = 0;
// for (Testcase testc : testcases) {
// TextView tvok = testc.getTextViewOk();
// TextView tverror = testc.getTextViewError();
// if (testc.isExecute()) {
// if (testc.isSuccsess()) {
// tvok.setText(result.get(r));
// tvok.setTextColor(getResources().getColor(R.color.green));
// tverror.setText(result.get(r+1));
// tverror.setTextColor(getResources().getColor(R.color.orange));
// }
// else {
// tvok.setText(result.get(r));
// tvok.setTextColor(getResources().getColor(R.color.red));
// tverror.setText(result.get(r+1));
// tverror.setTextColor(getResources().getColor(R.color.white));
// }
// }
// else {
// tvok.setText(result.get(r));
// tvok.setTextColor(getResources().getColor(R.color.red));
// tverror.setText(result.get(r+1));
// tverror.setTextColor(getResources().getColor(R.color.white));
// }
// r = r + 2;
// }
// progressdialog.dismiss();
}
}
private void sendMms() {
int responseCode=0;
for (Testcase testc : testcases) {
error = "";
if (testc.isExecute()) {
File file = new File(Environment.getExternalStorageDirectory(), ".MODTest/" + testc.getContentFile());
if (file.exists()) {
if (file.length() > 300000) {
Log.v(TAG, "File Length="+ Long.toString(file.length()));
error=getResources().getString(R.string.warningFileSize);
}
responseCode = sendMms.startMms(testc.getSubject(), number, apn, testc.getContentFile(), testc.getContentType(), getApplicationContext());
Log.v(TAG,"Test: "+ testc.getName() + " / Response code: " + Integer.toString(responseCode));
if (responseCode == 200) {
testc.setSuccsess(true);
responseCode = 0;
} else {
testc.setSuccsess(false);
error =Integer.toString(responseCode);
}
} else {
testc.setSuccsess(false);
error =getResources().getString(R.string.errorNoFile);
}
if (testc.isSuccsess()) {
resultarray.add(getResources().getString(R.string.ok) + " ");
resultarray.add(error);
} else {
resultarray.add(getResources().getString(R.string.failed) + " ");
resultarray.add(error);
}
} else {
resultarray.add(getResources().getString(R.string.notExe));
resultarray.add(error);
}
testc.setRunning(true);
myTask.onProgressUpdate(resultarray.get(resultarray.size()-2), resultarray.get(resultarray.size()-1));
}
endMmsConnectivity();
mSending = false;
mListening = false;
}
public void startMms() {
for (Testcase tcs : testcases) {
testcase = tcs;
number = number + "/TYPE=PLMN";
// IntentFilter filter = new IntentFilter();
// filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
// registerReceiver(mReceiver, filter);
try {
// Ask to start the connection to the APN. Pulled from Android
// source code.
int result = beginMmsConnectivity();
Log.v(TAG, "Result= " + Integer.toString(result));
if (result != PhoneEx.APN_ALREADY_ACTIVE) {
Log.v(TAG, "Extending MMS connectivity returned " + result
+ " instead of APN_ALREADY_ACTIVE");
// Just wait for connectivity startup without
// any new request of APN switch.
return;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void sendSms(String nr, Testcase tc) {
if (!tc.getBody().equals("")) {
SmsManager sm = SmsManager.getDefault();
sm.getDefault().sendTextMessage(nr, null, tc.getBody(), null, null);
tc.setSuccsess(true);
} else {
tc.setSuccsess(false);
error = getResources().getString(R.string.errorEmptySms);
}
}
#Override
public void onClick(View v) {
if (v.equals(findViewById(R.id.btnBack))) { // Wenn Button zurück
// geklickt wird
Intent startMmsTest = new Intent(ReportActivity.this,
StartActivity.class);
startActivity(startMmsTest);
}
}
protected void endMmsConnectivity() {
// End the connectivity
try {
Log.v(TAG, "endMmsConnectivity");
if (mConnMgr != null) {
mConnMgr.stopUsingNetworkFeature(
ConnectivityManager.TYPE_MOBILE,
PhoneEx.FEATURE_ENABLE_MMS);
}
} finally {
releaseWakeLock();
}
}
protected int beginMmsConnectivity() throws IOException {
// Take a wake lock so we don't fall asleep before the message is
// downloaded.
createWakeLock();
int result = mConnMgr.startUsingNetworkFeature(
ConnectivityManager.TYPE_MOBILE, PhoneEx.FEATURE_ENABLE_MMS);
Log.v(TAG, "beginMmsConnectivity: result=" + result);
switch (result) {
case PhoneEx.APN_ALREADY_ACTIVE:
case PhoneEx.APN_REQUEST_STARTED:
acquireWakeLock();
return result;
}
throw new IOException("Cannot establish MMS connectivity");
}
private synchronized void createWakeLock() {
// Create a new wake lock if we haven't made one yet.
if (mWakeLock == null) {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"MMS Connectivity");
mWakeLock.setReferenceCounted(false);
}
}
private void acquireWakeLock() {
// It's okay to double-acquire this because we are not using it
// in reference-counted mode.
mWakeLock.acquire();
}
private void releaseWakeLock() {
// Don't release the wake lock if it hasn't been created and acquired.
if (mWakeLock != null && mWakeLock.isHeld()) {
mWakeLock.release();
}
}
private class ConnectivityBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
int responseCode;
String action = intent.getAction();
if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)
|| mListening == false) {
Log.w(TAG, "onReceived() called with " + mState.toString()
+ " and " + intent);
return;
}
boolean noConnectivity = intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
if (noConnectivity) {
mState = State.NOT_CONNECTED;
} else {
mState = State.CONNECTED;
}
mNetworkInfo = (NetworkInfo) intent
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
// mOtherNetworkInfo = (NetworkInfo) intent
// .getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
// mReason =
// intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
// mIsFailover =
// intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER,
// false);
// Check availability of the mobile network.
if (mNetworkInfo == null) {
/**
* || (mNetworkInfo.getType() !=
* ConnectivityManager.TYPE_MOBILE)) {
*/
Log.v(TAG, " type is not TYPE_MOBILE_MMS, bail");
return;
}
if (!mNetworkInfo.isConnected()) {
Log.v(TAG, " TYPE_MOBILE_MMS not connected, bail");
return;
} else {
Log.v(TAG, "connected..");
if (mSending == false) {
mSending = true;
sendMms();
}
}
}
}
}
Move it to onProgressUpdate() method, or better , onPostExecute()/onPreExecuteMethod() depending on your need.
These methods run on UI thread and not on the new thread creetaed by the Asynctask

Can not access SharedPreferences value in another class after restart

I am using csipsimple code and customised it to show brandname by getting json value from webservice . I am using SharedPreferences to store value .
Once the application is force closed , or device restart SharedPreferences are lost . I am using commit and clear but still the values are null .
BasePrefsWizard is the class responsible for pulling web data and DialerFragment is the other class i am calling the BrandName ( it is SavedBrand/ brand in code)
package com.mydial.wizards;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.preference.EditTextPreference;
import android.util.Base64;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.mydial.api.SipManager;
import com.mydial.api.SipProfile;
import com.mydial.db.DBProvider;
import com.mydial.models.Filter;
import com.mydial.ui.SipHome;
import com.mydial.ui.dialpad.DialerFragment;
import com.mydial.ui.filters.AccountFilters;
import com.mydial.ui.prefs.GenericPrefs;
import com.mydial.utils.AccountListUtils;
import com.mydial.utils.Log;
import com.mydial.utils.PreferencesProviderWrapper;
import com.mydial.utils.PreferencesWrapper;
import com.mydial.utils.AccountListUtils.AccountStatusDisplay;
import com.mydial.utils.animation.ActivitySwitcher;
import com.mydial.wizards.WizardUtils.WizardInfo;
import com.mydial.wizards.impl.Advanced;
import com.worldfone.R;
#SuppressLint("NewApi") public class BasePrefsWizard extends GenericPrefs {
public static final int SAVE_MENU = Menu.FIRST + 1;
public static final int TRANSFORM_MENU = Menu.FIRST + 2;
public static final int FILTERS_MENU = Menu.FIRST + 3;
public static final int DELETE_MENU = Menu.FIRST + 4;
private PreferencesProviderWrapper prefProviderWrapper;
private static final String THIS_FILE = "Base Prefs wizard";
protected SipProfile account = null;
private Button saveButton,cancel;
private String wizardId = "";
private WizardIface wizard = null;
private BroadcastReceiver mReceiver;
IntentFilter intentFilter;
public static final String myData = "mySharedPreferences";
public static String bal = null;
public static String sip = null;
public static String header = null;
public static String date = null;
public static String savedBal="";
public static String savedSip="";
public static String savedBrand="";
public static String webArray[] =new String[6];
#Override
protected void onCreate(Bundle savedInstanceState)
{
// Get back the concerned account and if any set the current (if not a
// new account is created)
Intent intent = getIntent();
long accountId = 1;
//intent.getLongExtra(SipProfile.FIELD_ID, SipProfile.INVALID_ID);
// TODO : ensure this is not null...
// setWizardId(intent.getStringExtra(SipProfile.FIELD_WIZARD));
setWizardId();
account = SipProfile.getProfileFromDbId(this, accountId, DBProvider.ACCOUNT_FULL_PROJECTION);
super.onCreate(savedInstanceState);
prefProviderWrapper = new PreferencesProviderWrapper(this);
// Bind buttons to their actions
cancel = (Button) findViewById(R.id.cancel_bt);
//cancel.setEnabled(false);
cancel.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
isOnline();
//saveAndFinish();
}
});
saveButton = (Button) findViewById(R.id.save_bt);
//saveButton.setEnabled(false);
saveButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
//setResult(RESULT_CANCELED, getIntent());
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
finish();
System.exit(0);
}
});
wizard.fillLayout(account);
loadValue();
}
public void isOnline()
{
ConnectivityManager connMgr = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
{
try
{
String webAccessNumberLink="http://myweblink.info/test/code.php?user=1234";
new webAccessNumber().execute(webAccessNumberLink);
}
catch(Exception e)
{
// System.out.println("exception in basepreference "+e);
}
}
else
{
// display error
showNetworkAlert();
}
}
void showNetworkAlert()
{
new AlertDialog.Builder(this)
.setTitle("Alert")
.setMessage(
"Please make sure you have Network Enabled")
.setNeutralButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
/*Intent siphome = new Intent(getApplicationContext(),SipHome.class);
startActivity(siphome);*/
}
}).show();
}
public void saveArray(String[] arrayOfweb)
{
int mode = Context.MODE_PRIVATE;
SharedPreferences mySharedPreferences =this.getSharedPreferences(myData,
mode);
SharedPreferences.Editor editor = mySharedPreferences.edit();
String f1 = arrayOfweb[0];
String f2 = arrayOfweb[1];
String f3 = arrayOfweb[2];
String f4 = arrayOfweb[3];
for(int i=0;i<arrayOfweb.length;i++)
{
}
//byMe added below to make preferences persistant
editor.clear();
editor.putString("balance",f1);
editor.putString("sipp",f2);
editor.putString("brand",f3);
editor.putString("prfx",f4);
editor.commit();
loadValue();
}
private void loadValue()
{
int mode = Context.MODE_PRIVATE;
SharedPreferences mySharedPreferences = this.getSharedPreferences(myData,
mode);
savedBal= mySharedPreferences.getString("balance", "");
savedSip = mySharedPreferences.getString("sipp", "");
savedBrand = mySharedPreferences.getString("barnd", "");
}
private boolean isResumed = false;
#Override
protected void onResume()
{
super.onResume();
isResumed = true;
updateDescriptions();
updateValidation();
//byMe
}
#Override
protected void onPause()
{
super.onPause();
isResumed = false;
//this.unregisterReceiver(this.mReceiver);
}
private boolean setWizardId()
{
try {
wizard=Advanced.class.newInstance();
// wizard = (WizardIface) wizardInfo.classObject.newInstance();
} catch (IllegalAccessException e) {
Log.e(THIS_FILE, "Can't access wizard class", e);
/*if (!wizardId.equals(WizardUtils.EXPERT_WIZARD_TAG)) {
return setWizardId(WizardUtils.EXPERT_WIZARD_TAG);
}*/
return false;
} catch (InstantiationException e) {
Log.e(THIS_FILE, "Can't access wizard class", e);
/* if (!wizardId.equals(WizardUtils.EXPERT_WIZARD_TAG)) {
return setWizardId(WizardUtils.EXPERT_WIZARD_TAG);
}
*/ return false;
}
//wizardId = wId;
wizard.setParent(this);
if(getSupportActionBar() != null) {
getSupportActionBar().setIcon(WizardUtils.getWizardIconRes(wizardId));
}
return true;
}
private boolean setWizardId(String wId) {
if (wizardId == null) {
return setWizardId(WizardUtils.EXPERT_WIZARD_TAG);
}
WizardInfo wizardInfo = WizardUtils.getWizardClass(wId);
if (wizardInfo == null) {
if (!wizardId.equals(WizardUtils.EXPERT_WIZARD_TAG)) {
return setWizardId(WizardUtils.EXPERT_WIZARD_TAG);
}
return false;
}
try {
wizard = (WizardIface) wizardInfo.classObject.newInstance();
} catch (IllegalAccessException e) {
Log.e(THIS_FILE, "Can't access wizard class", e);
if (!wizardId.equals(WizardUtils.EXPERT_WIZARD_TAG)) {
return setWizardId(WizardUtils.EXPERT_WIZARD_TAG);
}
return false;
} catch (InstantiationException e) {
Log.e(THIS_FILE, "Can't access wizard class", e);
if (!wizardId.equals(WizardUtils.EXPERT_WIZARD_TAG)) {
return setWizardId(WizardUtils.EXPERT_WIZARD_TAG);
}
return false;
}
wizardId = wId;
wizard.setParent(this);
if(getSupportActionBar() != null) {
getSupportActionBar().setIcon(WizardUtils.getWizardIconRes(wizardId));
}
return true;
}
#Override
protected void beforeBuildPrefs() {
// Use our custom wizard view
setContentView(R.layout.wizard_prefs_base);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(isResumed) {
updateDescriptions();
updateValidation();
}
}
private void resolveStatus()
{
AccountStatusDisplay accountStatusDisplay = AccountListUtils
.getAccountDisplay(this, 1);
//status.setTextColor(accountStatusDisplay.statusColor);
//status.setText(accountStatusDisplay.statusLabel);
}
/**
* Update validation state of the current activity.
* It will check if wizard can be saved and if so
* will enable button
*/
public void updateValidation()
{
cancel.setEnabled(wizard.canSave());
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
// menu.findItem(SAVE_MENU).setVisible(wizard.canSave());
return super.onPrepareOptionsMenu(menu);
}
private static final int CHOOSE_WIZARD = 0;
private static final int MODIFY_FILTERS = CHOOSE_WIZARD + 1;
private static final int FINAL_ACTIVITY_CODE = MODIFY_FILTERS;
private int currentActivityCode = FINAL_ACTIVITY_CODE;
public int getFreeSubActivityCode()
{
currentActivityCode ++;
return currentActivityCode;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
}
/**
* Save account and end the activity
*/
public void saveAndFinish()
{
//this.registerReceiver(mReceiver, intentFilter);
saveAccount();
Intent intent = getIntent();
setResult(RESULT_OK, intent);
Intent it = new Intent(this,SipHome.class);
startActivity(it);
finish();
}
void updateStatus()
{
AccountStatusDisplay accountStatusDisplay = AccountListUtils
.getAccountDisplay(this, account.id);
}
/*
* Save the account with current wizard id
*/
private void saveAccount() {
saveAccount(wizardId);
}
#Override
protected void onDestroy() {
//byMe
super.onDestroy();
getSharedPreferences(WIZARD_PREF_NAME, MODE_PRIVATE).edit().clear().commit();
saveArray(webArray);
}
/**
* Save the account with given wizard id
* #param wizardId the wizard to use for account entry
*/
private void saveAccount(String wizardId) {
boolean needRestart = false;
PreferencesWrapper prefs = new PreferencesWrapper(getApplicationContext());
account = wizard.buildAccount(account);
account.wizard = wizardId;
if (account.id == SipProfile.INVALID_ID) {
// This account does not exists yet
prefs.startEditing();
wizard.setDefaultParams(prefs);
prefs.endEditing();
Uri uri = getContentResolver().insert(SipProfile.ACCOUNT_URI, account.getDbContentValues());
// After insert, add filters for this wizard
account.id = ContentUris.parseId(uri);
List<Filter> filters = wizard.getDefaultFilters(account);
if (filters != null) {
for (Filter filter : filters) {
// Ensure the correct id if not done by the wizard
filter.account = (int) account.id;
getContentResolver().insert(SipManager.FILTER_URI, filter.getDbContentValues());
}
}
// Check if we have to restart
needRestart = wizard.needRestart();
} else {
// TODO : should not be done there but if not we should add an
// option to re-apply default params
prefs.startEditing();
wizard.setDefaultParams(prefs);
prefs.endEditing();
getContentResolver().update(ContentUris.withAppendedId(SipProfile.ACCOUNT_ID_URI_BASE, account.id), account.getDbContentValues(), null, null);
}
// Mainly if global preferences were changed, we have to restart sip stack
if (needRestart) {
Intent intent = new Intent(SipManager.ACTION_SIP_REQUEST_RESTART);
sendBroadcast(intent);
}
}
#Override
protected int getXmlPreferences() {
return wizard.getBasePreferenceResource();
}
#Override
protected void updateDescriptions() {
wizard.updateDescriptions();
}
#Override
protected String getDefaultFieldSummary(String fieldName) {
return wizard.getDefaultFieldSummary(fieldName);
}
private static final String WIZARD_PREF_NAME = "Wizard";
#Override
public SharedPreferences getSharedPreferences(String name, int mode) {
return super.getSharedPreferences(WIZARD_PREF_NAME, mode);
}
private class webAccessNumber extends AsyncTask<String, Void, String>
{
//String balance;
ProgressDialog progressDialog;
#Override
protected String doInBackground(String... params) {
return getAccessNumber(params[0]);
}
#Override
protected void onPostExecute(String result)
{
if(result!=null)
{
try {
System.out.println("value of webAccessNumber "+result);
byte[] decoded = Base64.decode(result,Base64.DEFAULT);
String decodedStr =new String(decoded, "UTF-8");
//System.out.println(decodedStr);
JSONArray arr = new JSONArray(decodedStr);
//loop through each object
for (int i=0; i<arr.length(); i++)
{
JSONObject jsonObject = arr.getJSONObject(i);
bal = jsonObject.getString("balance");
sip = jsonObject.getString("server");
header = jsonObject.getString("brand");
webArray[1]=bal;
webArray[2]=sip;
webArray[3]=barnd;
saveArray(webArray);
saveAndFinish();
progressDialog.dismiss();
}
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(BasePrefsWizard.this);
progressDialog.setMessage("Loading..............");
progressDialog.setIndeterminate(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(true);
progressDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
}
public String getAccessNumber(String b) {
String balance = "";
String currency = "USD";
try {
balance = DownloadText(b).trim();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return balance;
}
String DownloadText(String URL) {
int BUFFER_SIZE = 2000;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return "";
}
InputStreamReader isr = new InputStreamReader(in);
int charRead;
String str = "";
char[] inputBuffer = new char[BUFFER_SIZE];
try {
while ((charRead = isr.read(inputBuffer)) > 0) {
String readString = String.copyValueOf(inputBuffer, 0,
charRead);
str += readString;
inputBuffer = new char[BUFFER_SIZE];
}
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
return str;
}
InputStream OpenHttpConnection(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
return in;
}
}//end of webAccessNumber asynchronus
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
{
isOnline();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
You should not clear the SharedPreferences in the onDestroy() method, because when you run your activity or your application again, all the saved values and variables in preferences are deleted, ( like you installed your application for the first time).
PS : here is a tutorial about Using SharedPreferences and Storing Data in Android
You are clearing your preferences in your code,
#Override
protected void onDestroy() {
//byMe
super.onDestroy();
//Preferences cleared
getSharedPreferences(WIZARD_PREF_NAME, MODE_PRIVATE).edit().clear().commit();
saveArray(webArray);
}
This is clearing your preferences.
You are clearing the shared prefereence in onDestroy:
#Override
protected void onDestroy() {
//byMe
super.onDestroy();
getSharedPreferences(WIZARD_PREF_NAME, MODE_PRIVATE).edit().clear().commit(); // <-- Remove this
saveArray(webArray);
}
You delete it in:
#Override
protected void onDestroy() {
super.onDestroy();
getSharedPreferences(WIZARD_PREF_NAME, MODE_PRIVATE).edit().clear().commit();
saveArray(webArray);
}
Also see this http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

unable to insert into azure via android application

im doing a login register for my application and i have to integrate them together with microsoft azure. However, despite after following the tutorial given by microsoft azure, i still fail to insert my "string" into their database. There are also no error in the codes, hence i'm not very sure where is wrong. Below is my codes.
package mp.memberuse;
import java.net.MalformedURLException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import com.microsoft.windowsazure.mobileservices.*;
public class LoginRegister extends Activity {
Button btn1, btn2, btn3;
EditText tf1, tf2, tf3, tf4, tf5, tf6, tf7, tf8, tf9, tf10, tf11;
TextView tv1, tv2;
private MobileServiceClient mClient;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TabHost tabs = (TabHost) this.findViewById(R.id.lt2tabhost);
tabs.setup();
TabSpec ts1 = tabs.newTabSpec("Login");
ts1.setIndicator("Login");
ts1.setContent(R.id.c1);
tabs.addTab(ts1);
TabSpec ts2 = tabs.newTabSpec("Register");
ts2.setIndicator("Register");
ts2.setContent(R.id.c2);
tabs.addTab(ts2);
btn1 = (Button)findViewById(R.id.button1);
btn2 = (Button)findViewById(R.id.button2);
btn3 = (Button)findViewById(R.id.button3);
tf1=(EditText) findViewById(R.id.editText1);
tf2=(EditText) findViewById(R.id.editText2);
tf3=(EditText) findViewById(R.id.editText3);
tf4=(EditText) findViewById(R.id.editText4);
tf5=(EditText) findViewById(R.id.editText5);
tf6=(EditText) findViewById(R.id.editText6);
tf7=(EditText) findViewById(R.id.editText7);
tf8=(EditText) findViewById(R.id.editText8);
tf9=(EditText) findViewById(R.id.editText9);
tf10=(EditText) findViewById(R.id.editText10);
tv1=(TextView) findViewById(R.id.login);
tv2=(TextView) findViewById(R.id.register);
try {
MobileServiceClient mClient = new MobileServiceClient("https://testrun.azure-mobile.net/","FOJanABDYiJEVMHkCECAylrXJCnVwF77",this);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
btn1.setOnClickListener(new View.OnClickListener(){
public void onClick(View v)
{
String username, password;
username = tf1.getText().toString();
password = tf2.getText().toString();
/**if(username.equals(sqlusername) && password.equals(sqlpassword))
{
SharedPreferences prefs = getSharedPreferences("myPreferences",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("fullname", fullname);
editor.commit();
Intent intent = new Intent(LoginRegister.this, SendMessage.class);
startActivity(intent);
}
else
{
tv1.setText("Invalid user");
} **/
}
}
);
btn2.setOnClickListener(new View.OnClickListener(){
public void onClick(View v)
{
String username, password, cpassword, fullname, nric, address, phone, email;
username = tf3.getText().toString();
password = tf4.getText().toString();
cpassword = tf5.getText().toString();
fullname = tf6.getText().toString();
nric = tf7.getText().toString();
address = tf8.getText().toString();
phone = tf9.getText().toString();
email = tf10.getText().toString();
Members members = new Members();
members.username = username;
members.password = password;
members.fullname = fullname;
members.nric = nric;
members.address = address;
members.phone = phone;
members.email = email;
if(!password.equals(cpassword))
{
tv2.setText("Password & Confirm Password does not match.");
}
else if(username.equals("") || password.equals("") || cpassword.equals("") || fullname.equals("") || nric.equals("") || address.equals("") || phone.equals("") || email.equals(""))
{
tv2.setText("Do not leave any field empty.");
}
else
{
mClient.getTable(Members.class).insert(members, new TableOperationCallback<Members>()
{
public void onCompleted(Members entity, Exception exception, ServiceFilterResponse response)
{
if (exception == null)
{
tv2.setText("Register Complete.");
tf3.setText("");
tf4.setText("");
tf5.setText("");
tf6.setText("");
tf7.setText("");
tf8.setText("");
tf9.setText("");
tf10.setText("");
}
else
{
tv2.setText("Fail to register!");
}
}
});
tv2.setText("Register Complete.");
tf3.setText("");
tf4.setText("");
tf5.setText("");
tf6.setText("");
tf7.setText("");
tf8.setText("");
tf9.setText("");
tf10.setText("");
}
}
});
btn3.setOnClickListener(new View.OnClickListener(){
public void onClick(View v)
{
tf3.setText("");
tf4.setText("");
tf5.setText("");
tf6.setText("");
tf7.setText("");
tf8.setText("");
tf9.setText("");
tf10.setText("");
}
});
}
}
Here is an code snippet , hoping it will help you.
1)An function which carries the http get service
private String SendDataFromAndroidDevice() {
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet getMethod = new HttpGet("your url + data appended");
BufferedReader in = null;
BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient
.execute(getMethod);
in = new BufferedReader(new InputStreamReader(httpResponse
.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
}
in.close();
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
2) An Class which extends AsyncTask
private class HTTPdemo extends
AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... params) {
String result = SendDataFromAndroidDevice();
return result;
}
#Override
protected void onProgressUpdate(Void... values) {}
#Override
protected void onPostExecute(String result) {
if (result != null && !result.equals("")) {
try {
JSONObject resObject = new JSONObject(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
3) Inside your onCreate method
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView("your layout");
if ("check here where network/internet is avaliable") {
new HTTPdemo().execute("");
}
}
The code snippet provided by me works in the following way,
1)Android device send the URL+data to server
2)Server [Azure platform used] receive the data and gives an acknowledgement
Now the Code which should be written at client side (Android) is provided to you, the later part of receiving that data at server is
Server needs to receive the data
An webservice should be used to do that
Implement an webservice at server side
The webservice will be invoked whenever android will push the URL+data
Once you have the data ,manipulated it as you want

Categories

Resources