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

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.

Related

How to send data sent by BLE Device in a fragment to a new activity for display and plotting graph in app?

I am completely new to Android and just learned Object-oriented programming. My project requires me to build something on open-source code. I am really struggling with this special case. Two fragments are under activity_main, one of them is TerminalFragment. I added a menuItem (R.id.plot) in it and set if the user clicks this Item that will lead him from TerminalFragment to activity_main2. Due to receive(byte data) and TerminalFragment still on active, the data is still printing out by receiveText.append(TextUtil.toCaretString(msg, newline.length() != 0)); in activity_main.
Now, I want to convert the data to String and send it to activity_main2 for display in recyclerview and plotting graph. I am trying to use putextra and getextra but not sure how to access data from getextra in activity_main2. In my testing, the recyclerview just showed "John". Is something missing in my method? Does anyone have a better idea? Much Appreciated.
TerminalFragment
package de.kai_morich.simple_bluetooth_le_terminal;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.ScrollingMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.EditText;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class TerminalFragment extends Fragment implements ServiceConnection, SerialListener {
private MenuItem menuItem;
private enum Connected { False, Pending, True }
private String deviceAddress;
private SerialService service;
private TextView receiveText;
private TextView sendText;
private TextUtil.HexWatcher hexWatcher;
private Connected connected = Connected.False;
private boolean initialStart = true;
private boolean hexEnabled = false;
private boolean pendingNewline = false;
private String newline = TextUtil.newline_crlf;
private String output;
/*
* Lifecycle
*/
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
//Register with activity
// You must inform the system that your app bar fragment is participating in the population of the options menu.
// tells the system that your fragment would like to receive menu-related callbacks.
setRetainInstance(true);
deviceAddress = getArguments().getString("device");
}
#Override
public void onDestroy() {
if (connected != Connected.False)
disconnect();
getActivity().stopService(new Intent(getActivity(), SerialService.class));
super.onDestroy();
}
#Override
public void onStart() {
super.onStart();
if(service != null)
service.attach(this);
else
getActivity().startService(new Intent(getActivity(), SerialService.class)); // prevents service destroy on unbind from recreated activity caused by orientation change
}
#Override
public void onStop() {
if(service != null && !getActivity().isChangingConfigurations())
service.detach();
super.onStop();
}
#SuppressWarnings("deprecation") // onAttach(context) was added with API 23. onAttach(activity) works for all API versions
#Override
public void onAttach(#NonNull Activity activity) {
super.onAttach(activity);
getActivity().bindService(new Intent(getActivity(), SerialService.class), this, Context.BIND_AUTO_CREATE);
}
#Override
public void onDetach() {
try { getActivity().unbindService(this); } catch(Exception ignored) {}
super.onDetach();
}
#Override
public void onResume() {
super.onResume();
if(initialStart && service != null) {
initialStart = false;
getActivity().runOnUiThread(this::connect);
}
}
#Override
public void onServiceConnected(ComponentName name, IBinder binder) {
service = ((SerialService.SerialBinder) binder).getService();
service.attach(this);
if(initialStart && isResumed()) {
initialStart = false;
getActivity().runOnUiThread(this::connect);
}
}
#Override
public void onServiceDisconnected(ComponentName name) {
service = null;
}
/*
* UI
*/
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_terminal, container, false);
receiveText = view.findViewById(R.id.receive_text); // TextView performance decreases with number of spans
receiveText.setTextColor(getResources().getColor(R.color.colorRecieveText)); // set as default color to reduce number of spans
receiveText.setMovementMethod(ScrollingMovementMethod.getInstance());
sendText = view.findViewById(R.id.send_text);
hexWatcher = new TextUtil.HexWatcher(sendText);
hexWatcher.enable(hexEnabled);
sendText.addTextChangedListener(hexWatcher);
sendText.setHint(hexEnabled ? "HEX mode" : "");
View sendBtn = view.findViewById(R.id.send_btn);
sendBtn.setOnClickListener(v -> send(sendText.getText().toString()));
return view;
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_terminal, menu);
menu.findItem(R.id.hex).setChecked(hexEnabled);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.clear) {
receiveText.setText("");
return true;
} if (id == R.id.plot){
Intent intent = new Intent(getActivity(), MainActivity2.class);
startActivity(intent);
//receive.;
return true;
}else if (id == R.id.newline) {
String[] newlineNames = getResources().getStringArray(R.array.newline_names);
String[] newlineValues = getResources().getStringArray(R.array.newline_values);
int pos = java.util.Arrays.asList(newlineValues).indexOf(newline);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Newline");
builder.setSingleChoiceItems(newlineNames, pos, (dialog, item1) -> {
newline = newlineValues[item1];
dialog.dismiss();
});
builder.create().show();
return true;
} else if (id == R.id.hex) {
hexEnabled = !hexEnabled;
sendText.setText("");
hexWatcher.enable(hexEnabled);
sendText.setHint(hexEnabled ? "HEX mode" : "");
item.setChecked(hexEnabled);
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
/*
* Serial + UI
*/
private void connect() {
try {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
status("connecting...");
connected = Connected.Pending;
SerialSocket socket = new SerialSocket(getActivity().getApplicationContext(), device);
service.connect(socket);
} catch (Exception e) {
onSerialConnectError(e);
}
}
private void disconnect() {
connected = Connected.False;
service.disconnect();
}
private void send(String str) {
if(connected != Connected.True) {
Toast.makeText(getActivity(), "not connected", Toast.LENGTH_SHORT).show();
return;
}
try {
String msg;
byte[] data;
if(hexEnabled) {
StringBuilder sb = new StringBuilder();
TextUtil.toHexString(sb, TextUtil.fromHexString(str));
TextUtil.toHexString(sb, newline.getBytes());
msg = sb.toString();
data = TextUtil.fromHexString(msg);
} else {
msg = str;
data = (str + newline).getBytes();
}
SpannableStringBuilder spn = new SpannableStringBuilder(msg + '\n');
spn.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorSendText)), 0, spn.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
receiveText.append(spn);
service.write(data);
} catch (Exception e) {
onSerialIoError(e);
}
}
private void receive(byte[] data) {
if(hexEnabled) {
receiveText.append("Hello" + TextUtil.toHexString(data) + '\n');
} else {
String msg = new String(data);
if(newline.equals(TextUtil.newline_crlf) && msg.length() > 0) {
// don't show CR as ^M if directly before LF
msg = msg.replace(TextUtil.newline_crlf, TextUtil.newline_lf);
// special handling if CR and LF come in separate fragments
if (pendingNewline && msg.charAt(0) == '\n') {
Editable edt = receiveText.getEditableText();
if (edt != null && edt.length() > 1)
edt.replace(edt.length() - 2, edt.length(), "");
}
pendingNewline = msg.charAt(msg.length() - 1) == '\r';
}
receiveText.append(TextUtil.toCaretString(msg, newline.length() != 0)); //print out data
output = receiveText.toString(); // CharSequence to String
Intent intent = new Intent(getActivity(), MainActivity2.class);
intent.putExtra("output",output); // send data to next activity, MainActivity2
}
}
private void status(String str) {
SpannableStringBuilder spn = new SpannableStringBuilder(str + '\n');
spn.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorStatusText)), 0, spn.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
receiveText.append(spn);
}
/*
* SerialListener
*/
#Override
public void onSerialConnect() {
status("connected");
connected = Connected.True;
}
#Override
public void onSerialConnectError(Exception e) {
status("connection failed: " + e.getMessage());
disconnect();
}
#Override
public void onSerialRead(byte[] data) {// receive data
receive(data); // send data to printout
}
#Override
public void onSerialIoError(Exception e) {
status("connection lost: " + e.getMessage());
disconnect();
}
}
MainActivity2.java (new activity)
package de.kai_morich.simple_bluetooth_le_terminal;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity2 extends AppCompatActivity {
Fragment CustomFragment;
private ArrayList<Data> dataList;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = findViewById(R.id.toolbar2);
setSupportActionBar(toolbar);
recyclerView = findViewById(R.id.dataflow);
dataList = new ArrayList<>();
String data;
if (savedInstanceState == null) {
Bundle extra = getIntent().getExtras();
if (extra == null) {
data = null;
receiveData(data);
} else {
data = extra.getString("output");
receiveData(data);
}
} else {
data = (String) savedInstanceState.getSerializable("output");
receiveData(data);
}
setAdapter();
}
private void receiveData(String data){
String Data = data;
dataList.add(new Data("John"));
dataList.add(new Data(Data));
}
private void setAdapter() {
recyclerAdapter adapter = new recyclerAdapter(dataList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_plot, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.dataplot:
Toast.makeText(this, "dataplot", Toast.LENGTH_SHORT).show();
replaceFragment(new DataPlotFragment());
return true;
case R.id.fft:
Toast.makeText(this, "FFT", Toast.LENGTH_SHORT).show();
replaceFragment(new FftFragment());
return true;
case R.id.data:
Toast.makeText(this, "DATA", Toast.LENGTH_SHORT).show();
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void replaceFragment(Fragment fragment){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.plotframelayout,fragment);
fragmentTransaction.commit();
}
}
I realized I also need to add getText() in receive(). However, the recycler view won't update itself, it just captures what it has in the recyclerview of activity_main with TerminalFragment when the user click the menuItem (id,plot). Either getextrastring() or using bundle able to pass the data to Mainactivity2.
I think I need to add something else to keep adding data to the recyclerview of activity_main2 from activity_main.
onOptionsItemSelected of TerminalFragment
if (id == R.id.plot){
Intent intent = new Intent(getActivity(), MainActivity2.class);
intent.putExtra("output",output); //output
startActivity(intent);
return true;
}
receive() of TerminalFragment
private void receive(byte[] data) {
if(hexEnabled) {
receiveText.append("Hello" + TextUtil.toHexString(data) + '\n');
} else {
String msg = new String(data);
if(newline.equals(TextUtil.newline_crlf) && msg.length() > 0) {
// don't show CR as ^M if directly before LF
msg = msg.replace(TextUtil.newline_crlf, TextUtil.newline_lf);
// special handling if CR and LF come in separate fragments
if (pendingNewline && msg.charAt(0) == '\n') {
Editable edt = receiveText.getEditableText();
if (edt != null && edt.length() > 1)
edt.replace(edt.length() - 2, edt.length(), "");
}
pendingNewline = msg.charAt(msg.length() - 1) == '\r';
}
receiveText.append(TextUtil.toCaretString(msg, newline.length() != 0)); //print out data
output = receiveText.getText().toString(); // CharSequence to String
}
}
OnCreate of mainActivity2
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = findViewById(R.id.toolbar2);
setSupportActionBar(toolbar);
recyclerView = findViewById(R.id.dataflow);
dataList = new ArrayList<>();
String data;
Bundle extras = getIntent().getExtras();
if (extras != null)
{
data = extras.getString("output");
receiveData(data);
}
setAdapter();
}

Cannot get the value from sharedPrefenced

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, ""));
}
}

Google maps showing logo, but not displaying in Android emulator

My app is supposed to display a Google Map with a heatmap, but I can't even get the map to display. It's only showing the logo in the bottom left corner. There seems to be no errors. I also checked the gradle and all the necessary dependencies are there. I can't tell if this is due to an actual error or lack of memory/slow processing.
Here's the MainActivity
package com.example.alexlevine.oceanapp;
package com.example.alexlevine.oceanapp;
import android.app.Dialog;
import android.content.Intent;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.TileOverlayOptions;
import com.google.maps.android.heatmaps.HeatmapTileProvider;
import com.google.maps.android.heatmaps.WeightedLatLng;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
import static com.example.alexlevine.oceanapp.R.id.seekBar;
import static com.example.alexlevine.oceanapp.fetchSOCATData.co2array;
public class MainActivity extends AppCompatActivity
implements OnMapReadyCallback {
public static SeekBar seekbar;
public static GoogleMap mGoogleMap;
private HeatmapTileProvider mProvider;
public static TextView minyear;
public static TextView maxyear;
public static TextView currentyeartext;
public static int displayyear;
public static boolean usingSOCAT;
public static String typeKey;
public static Spinner dropdown;
private String[] mNavigationDrawerItemTitles;
private DrawerLayout mDrawerLayout;
android.support.v7.app.ActionBarDrawerToggle mDrawerToggle;
Button b2;
Button b4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (googleServicesAvailable()) {
Toast.makeText(this, "Play services available", Toast.LENGTH_LONG).show();;
initMap();
b2 = (Button) findViewById(R.id.button2);
b4 = (Button) findViewById(R.id.button4);
b2.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.button2) {
Intent i = new Intent(MainActivity.this, CarbonCalcActivity.class);
startActivity(i);
finish();
}
}
});
b4.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
if(v.getId() == R.id.button4) {
Intent i = new Intent(MainActivity.this, CalcData.class);
startActivity(i);
finish();
}
}
}
);
//get the spinner from the xml.
dropdown = (Spinner)findViewById(R.id.spinner);
//create a list of items for the spinner.
String[] items = new String[]{"Ocean CO2 Densities", "Land CO2 Emissions (all sources)", "Electricity CO2 Emissions", "Aviation CO2 Emissions", "Ocean Shipping CO2 Emissions"};
//create an adapter to describe how the items are displayed, adapters are used in several places in android.
//There are multiple variations of this, but this is the basic variant.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items);
//set the spinners adapter to the previously created one.
dropdown.setAdapter(adapter);
currentyeartext = (TextView) findViewById(R.id.currentyear);
minyear = (TextView) findViewById(R.id.minyear);
maxyear = (TextView) findViewById(R.id.maxyear);
typeKey = "00totals";
dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
switch (position) {
case 0: {
usingSOCAT = true;
displayyear = 1991;
seekbar.setMax(24);
minyear.setText("1991");
maxyear.setText("2015");
break;
}
case 1: {
usingSOCAT = false;
displayyear = 1997;
minyear.setText("1997");
maxyear.setText("2010");
seekbar.setMax(14);
typeKey = "00totals";
break;
}
case 2: {
usingSOCAT = false;
displayyear = 1997;
minyear.setText("1997");
maxyear.setText("2010");
seekbar.setMax(14);
typeKey = "01elec";
// Whatever you want to happen when the thrid item gets selected
break;
}
case 3: {
usingSOCAT = false;
displayyear = 1997;
minyear.setText("1997");
maxyear.setText("2010");
seekbar.setMax(14);
typeKey = "11aviation";;
// Whatever you want to happen when the thrid item gets selected
break;
}
case 4: {
usingSOCAT = false;
displayyear = 1997;
minyear.setText("1997");
maxyear.setText("2010");
seekbar.setMax(14);
typeKey = "12shipping";
// Whatever you want to happen when the thrid item gets selected
break;
}
}
}
public void onNothingSelected(AdapterView<?> parent)
{
}
});
seekbar = (SeekBar) findViewById(seekBar);
seekbar.setOnSeekBarChangeListener(
new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
displayyear = progress + 1991;
if(usingSOCAT)
{
displayyear = progress + 1991;
new fetchSOCATData().execute();
}
else
{
displayyear = progress + 1997;
new fetchFFDASData().execute();
//List<WeightedLatLng> calledData = fetchFFDASData.ffdasArray;
//createHeatMap(fetchFFDASData.ffdasArray);
minyear.setText((CharSequence) fetchFFDASData.ffdasArray);
}
currentyeartext.setText("Showing: " + displayyear);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
if(usingSOCAT) {
}
//new fetchSOCATData().execute();
/*minyear = (TextView) findViewById(R.id.minyear);
maxyear = (TextView) findViewById(R.id.maxyear);
minyear.setText("1957");
maxyear.setText("2015");*/
//fetchSOCATData process = new fetchSOCATData();
//process.execute();
} else {
//No maps layout
}
}
//#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void initMap() {
SupportMapFragment mapFragment = (SupportMapFragment) this.getSupportFragmentManager()
.findFragmentById(R.id.mapFragment);
if(mapFragment != null) {
mapFragment.getMapAsync((OnMapReadyCallback)this);
}
}
public void createHeatMap(List<WeightedLatLng> dataset)
{
List<WeightedLatLng> locations = dataset;
/*mProvider = new HeatmapTileProvider.Builder().weightedData(locations).build();
mProvider.setRadius( HeatmapTileProvider.DEFAULT_RADIUS );
mGoogleMap.addTileOverlay(new TileOverlayOptions().tileProvider(mProvider));
mProvider = new HeatmapTileProvider();
mProvider.setWeightedData(dataset);
mProvider = mProvider.build();*/
//for (LatLng coordinate : coordinates) {
//WeightedLatLng weightedCoordinate = new WeightedLatLng(coordinate);
//com.google.maps.android.geometry.Point point = weightedCoordinate.getPoint();
// Filter points at infinity
/* if (Double.isInfinite(point.x) || Double.isInfinite(point.y)) {
Log.w(TAG, "Attempted to add undefined point " + coordinate);
continue;
}
weightedCoordinates.add(weightedCoordinate);*/
//}
mProvider = new HeatmapTileProvider.Builder()
.weightedData(dataset)
.opacity(0.5)
.build();
mGoogleMap.addTileOverlay(new TileOverlayOptions().tileProvider(mProvider));
Toast.makeText(this, "working", Toast.LENGTH_SHORT).show();
}
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
//goToLocation(-65, -12);
}
public void goToLocation(double lat, double lng) {
LatLng ll = new LatLng(lat, lng);
CameraUpdate update = CameraUpdateFactory.newLatLng(ll);
mGoogleMap.moveCamera(update);
}
public boolean googleServicesAvailable() {
GoogleApiAvailability api = GoogleApiAvailability.getInstance();
int isAvailable = api.isGooglePlayServicesAvailable(this);
if (isAvailable == ConnectionResult.SUCCESS)
return true;
else if (api.isUserResolvableError(isAvailable)) {
Dialog dialog = api.getErrorDialog(this, isAvailable, 0);
dialog.show();
} else
Toast.makeText(this, "Can't connect to play services", Toast.LENGTH_LONG).show();
return false;
}
}
Here's my code to fetch the data for the heatmap:
package com.example.alexlevine.oceanapp;
import android.os.AsyncTask;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.Log;
import com.google.android.gms.maps.model.LatLng;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.maps.android.heatmaps.WeightedLatLng;
import java.io.IOException;
import java.lang.reflect.Type;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import static com.example.alexlevine.oceanapp.MainActivity.displayyear;
import static com.example.alexlevine.oceanapp.MainActivity.minyear;
#RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
public class fetchSOCATData extends AsyncTask<Object, Object, ArrayList<WeightedLatLng>> {
//String data = "http://ferret.pmel.noaa.gov/socat/erddap/tabledap/socat_v4_fulldata.geoJson?year%2Cmonth%2Cday%2Chour%2Cminute%2Csecond%2Clongitude%2Clatitude%2Csal%2CTemperature_equi%2CTemperature_atm%2CpCO2_atm_wet_actual%2Cdelta_fCO2%2Crelative_humidity%2Cspecific_humidity%2Cwind_speed_true%2Cwind_speed_rel%2Cwind_dir_true%2Cwind_dir_rel%2CfCO2_recommended%2Cregion_id%2Ctime&organization=%22%22";
//public static SOCATCO2DataPoint.FeaturesBean[] co2array;
public static List<WeightedLatLng> co2array;
#Override
protected ArrayList<WeightedLatLng> doInBackground(Object... params) {
co2array = new ArrayList<WeightedLatLng>();
int year = displayyear;
URL url = null;
try {
//url = new URL("http://ferret.pmel.noaa.gov/socat/erddap/tabledap/socat_v4_fulldata.geoJson?year%2Cmonth%2Cday%2Chour%2Cminute%2Csecond%2Clongitude%2Clatitude%2Csal%2CTemperature_equi%2CTemperature_atm%2CpCO2_atm_wet_actual%2Cdelta_fCO2%2Crelative_humidity%2Cspecific_humidity%2Cwind_speed_true%2Cwind_speed_rel%2Cwind_dir_true%2Cwind_dir_rel%2CfCO2_recommended%2Cregion_id%2Ctime&organization=%22%22&year%3E=2015&month%3C=1&day%3C=1&hour%3C=1&minute%3C=1&second%3C=10");
//url = new URL("http://ferret.pmel.noaa.gov/socat/erddap/tabledap/socat_v4_fulldata.json?year%2Clongitude%2Clatitude%2CfCO2_recommended%2Ctime&organization=%22%22&year%3E=" + year + "&year%3C=" + year);
//url = new URL("http://ferret.pmel.noaa.gov/socat/erddap/tabledap/socat_v4_fulldata.json?year%2Clongitude%2Clatitude%2CfCO2_recommended%2Ctime&organization=%22%22&year%3E=2015&year%3C=2015&month%3E=1&month%3C=1&day%3E=1&day%3C=1&hour%3E=1&hour%3C=1");
//url = new URL("http://ferret.pmel.noaa.gov/socat/erddap/tabledap/socat_v4_fulldata.geoJson?year%2Cmonth%2Cday%2Chour%2Cminute%2Csecond%2Clongitude%2Clatitude%2CfCO2_recommended%2Ctime&organization=%22%22&year%3E=" + year + "&year%3C=" + year);
url = new URL("http://ferret.pmel.noaa.gov/socat/erddap/tabledap/socat_v4_fulldata.json?longitude%2Clatitude%2CfCO2_recommended&organization=%22%22&year=" + displayyear + "&day=1&hour=1&minute%3C=5&second%3C=30&longitude!=NaN&longitude!=NaN&latitude!=NaN&latitude!=NaN");
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
Response response = null;
try {
response = client.newCall(request).execute();
} catch (IOException e1) {
e1.printStackTrace();
}
String result = null;
try {
result = response.body().string();
} catch (IOException e1) {
e1.printStackTrace();
}
//System.out.print("result" + result);
Gson gson = new Gson();
Type collectionType = new TypeToken<Collection<OfficialSOCATPoint.TableBean>>() {}.getType();
OfficialSOCATPoint enums = gson.fromJson(result, OfficialSOCATPoint.class);
//Collection<OfficialSOCATPoint.TableBean> enums = gson.fromJson(result, collectionType);
/*SOCATCO2DataPoint.FeaturesBean[] protoExtract = enums.toArray(new SOCATCO2DataPoint.FeaturesBean[enums.size()]);*/
OfficialSOCATPoint protoExtract = gson.fromJson(result, OfficialSOCATPoint.class);
//OfficialSOCATPoint.TableBean[] protoExtract = enums.toArray(new OfficialSOCATPoint.TableBean[enums.size()]);
List<List<String>> dataArray = (List<List<String>>) protoExtract.getTable().getRows();
//for (int i = 0; i < dataArray.size(); i++)
for (int i = 0; i < 2; i++)
{
if(dataArray.get(i).get(2) != "null" && dataArray.get(i).get(1) != "null" && dataArray.get(i).get(0) != "null")
{
//co2array.add(new WeightedLatLng(new LatLng(Double.parseDouble(dataArray.get(i).get(0)), Double.parseDouble(dataArray.get(i).get(1))), Double.parseDouble(dataArray.get(i).get(2))));
}
}
return (ArrayList<WeightedLatLng>) co2array;
}
//#Override
protected void onPostExecute(ArrayList<WeightedLatLng> fb) {
super.onPostExecute(fb);
}
}
Here's the logcat:
10-17 16:45:27.884 1583-1593/? W/WallpaperManagerService: Cannot extract colors because wallpaper could not be read.
10-17 16:45:27.886 1583-1593/? W/WallpaperManagerService: Cannot extract colors because wallpaper could not be read.
10-17 16:45:17.747 2160-2160/? W/zygote: Common causes for lock verification issues are non-optimized dex code
10-17 16:45:17.955 1583-1807/? W/WallpaperManagerService: Cannot extract colors because wallpaper could not be read.
10-17 16:45:19.896 2138-2227/? W/zygote: Common causes for lock verification issues are non-optimized dex code
10-17 16:45:28.114 2188-2312/? W/ErrorProcessor: onFatalError, processing error from engine(4)
com.google.android.apps.gsa.shared.speech.b.g: Error reading from input stream
at com.google.android.apps.gsa.staticplugins.recognizer.j.a.a(SourceFile:28)
at com.google.android.apps.gsa.staticplugins.recognizer.j.b.run(SourceFile:15)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:457)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:457)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at com.google.android.apps.gsa.shared.util.concurrent.a.ag.run(Unknown Source:4)
at com.google.android.apps.gsa.shared.util.concurrent.a.bo.run(SourceFile:4)
at com.google.android.apps.gsa.shared.util.concurrent.a.bo.run(SourceFile:4)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:6)
Caused by: com.google.android.apps.gsa.shared.exception.GsaIOException: Error code: 393238 | Buffer overflow, no available space.
at com.google.android.apps.gsa.speech.audio.Tee.f(SourceFile:103)
at com.google.android.apps.gsa.speech.audio.au.read(SourceFile:2)
at java.io.InputStream.read(InputStream.java:101)
at com.google.android.apps.gsa.speech.audio.ao.run(SourceFile:18)
at com.google.android.apps.gsa.speech.audio.an.run(SourceFile:2)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:457) 
at java.util.concurrent.FutureTask.run(FutureTask.java:266) 
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:457) 
at java.util.concurrent.FutureTask.run(FutureTask.java:266) 
at com.google.android.apps.gsa.shared.util.concurrent.a.ag.run(Unknown Source:4) 
at com.google.android.apps.gsa.shared.util.concurrent.a.bo.run(SourceFile:4) 
at com.google.android.apps.gsa.shared.util.concurrent.a.bo.run(SourceFile:4) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636) 
at java.lang.Thread.run(Thread.java:764) 
at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:6) 
10-17 16:45:38.815 2510-2510/? I/Finsky: [2] com.google.android.finsky.setup.VpaService.a(32): Should not show workaround PAI step because experiment disabled
10-17 16:45:48.416 1767-2047/? I/GCoreUlr: WorldUpdater:init: Ensuring that reporting is stopped because of reasons: (no Google accounts)
10-17 16:45:49.205 2069-2069/? I/MediaRouter: Unselecting the current route because it is no longer selectable: null
10-17 16:46:16.401 1767-2047/? W/NetworkScheduler: Immediate task was not started com.google.android.videos/.service.drm.RefreshLicenseTaskService{u=0 tag="refresh_license_forced" trigger=window{start=0s,end=1s,earliest=-1s,latest=0s} requirements=[NET_CONNECTED] attributes=[] scheduled=-1s last_run=N/A jid=N/A status=PENDING retries=0 client_lib=MANCHEGO_GCM-10400000}. Rescheduling immediate tasks can cause excessive battery drain.
10-17 16:46:16.928 1767-2047/? W/NetworkScheduler: Immediate task was not started com.google.android.gms/.tapandpay.gcmtask.TapAndPayGcmTaskService{u=0 tag="immediate" trigger=window{start=0s,end=1s,earliest=-1s,latest=0s} requirements=[NET_CONNECTED] attributes=[] scheduled=-1s last_run=N/A jid=N/A status=PENDING retries=0 client_lib=MANCHEGO_GCM-14366000}. Rescheduling immediate tasks can cause excessive battery drain.
Please help me with this. Thanks!

How to Show Different Strings With The Same Position When Clicking Random Button?

How to Show Different Strings With The Same Position When Clicking Random Button, So when the string is randomized the word and word2 display the same position data and in different textview. I have been looking for information for a few days and have not found an answer yet. I am confused to do so can you help me? Here's the Java file I have.
Adapter.java
package com.word.game;
import java.util.Random;
public class Adapter {
public static final Random RANDOM = new Random();
public static final String[] WORDS = {"RUN",
"WALK",
"CRY",
"SUGAR",
"SALT",
"RAIN",
"NOVEMBER"};
public static final String[] WORDS2 = {"FAST",
"RELAX",
"TEARS",
"DRINK",
"RECIPERS",
"WATER",
"CALENDAR"};
public static String randomWord2() {
return WORDS2[RANDOM.nextInt(WORDS2.length)];
}
public static String randomWord() {
return WORDS[RANDOM.nextInt(WORDS.length)];
}
public static String shuffleWord(String word) {
if (word != null && !"".equals(word)) {
char a[] = word.toCharArray();
for (int i = 0; i < a.length; i++) {
int j = RANDOM.nextInt(a.length);
char tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
return new String(a);
}
return word;
}
}
MainActivity.java
package com.papaozi.pilgub;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.InputFilter;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private MediaPlayer mediaPlayerbg, mediaPlayerwin, mediaPlayerSalah;
private TextView suffletext, quest;
private EditText answer;
private Button validate, newGame;
private String wordToFind, wordToFind2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
quest = (TextView) findViewById(R.id.quest);
suffletext = (TextView) findViewById(R.id.suffletext);
answer = (EditText) findViewById(R.id.wordEnteredEt);
validate = (Button) findViewById(R.id.validate);
validate.setOnClickListener(this);
newGame = (Button) findViewById(R.id.newGame);
newGame.setOnClickListener(this);
answer.setFilters(new InputFilter[]{new InputFilter.AllCaps()});
newGame();
initViews();
}
private void initViews() {
mediaPlayerbg = MediaPlayer.create(this, R.raw.spooky);
mediaPlayerbg.start();
mediaPlayerbg.setLooping(true);
}
#Override
public void onClick(View view) {
if (view == validate) {
validate();
} else if (view == newGame) {
newGame();
}
}
private void validate() {
String w = answer.getText().toString();
Context context = getApplicationContext();
LayoutInflater inflater = getLayoutInflater();
View customToastroot = inflater.inflate(R.layout.custom_toast_benar, null);
final Toast customtoast = new Toast(context);
customtoast.setView(customToastroot);
customtoast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP, 0, 0);
customtoast.setDuration(Toast.LENGTH_LONG);
Context context2 = getApplicationContext();
LayoutInflater inflater2 = getLayoutInflater();
View customToastroot2 = inflater2.inflate(R.layout.custom_toast_salah, null);
final Toast customtoast2 = new Toast(context2);
customtoast2.setView(customToastroot2);
customtoast2.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP, 0, 0);
customtoast2.setDuration(Toast.LENGTH_LONG);
if (wordToFind.equals(w)) {
customtoast.show();
newGame();
mediaPlayerwin = MediaPlayer.create(this, R.raw.winner);
mediaPlayerwin.start();
} else {
customtoast2.show();
mediaPlayerSalah = MediaPlayer.create(this, R.raw.draw);
mediaPlayerSalah.start();
}
}
private void newGame() {
wordToFind = Adapter.randomWord();
String wordShuffled = Adapter.shuffleWord(wordToFind);
suffletext.setText(wordShuffled);
answer.setText("");;
}
protected void onDestroy() {
super.onDestroy();
if (mediaPlayerbg != null) {
mediaPlayerbg.release();
mediaPlayerbg = null;
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new Intent(MainActivity.this, SecondActivity.class));
mediaPlayerbg.stop();
finish();
}
}
If you want to return same position in different arrays with same size,
Try this
public static String randomWord2(int pos) {
return WORDS2[pos];
}
public static String randomWord(int pos) {
return WORDS[pos];
}
public static int randomNum() {
return RANDOM.nextInt(WORDS.length);
}
When You are invoking randomWord() and randomWord2() , get the random position first and the pass it to the methods
int pos= randomNum();
word1=randomWord(pos);
word2=randomWord2(pos);

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

Categories

Resources