Используя SharedPreferences ... я сделал это правильно? - PullRequest
0 голосов
/ 02 февраля 2012

У меня есть подменю, которое содержит 3 варианта для пользователя.Каждый выбранный параметр вызывает одну из 3 функций, указанных ниже:

    void viewLast5Packets()
{
    userDefinedCount = 4;
    prefEditor.putString(lastpacketsPHP, "/* Put PHP file link here */");
    prefEditor.commit();
    assignInfoToHistoryTextView();
}

void viewLast10Packets()
{
    userDefinedCount = 9;
    prefEditor.putString(lastpacketsPHP, "/* Put PHP file link here */");
    prefEditor.commit();
    assignInfoToHistoryTextView();
}

void viewLast20Packets()
{
    userDefinedCount = 19;
    prefEditor.putString(lastpacketsPHP, "/* Put PHP file link here */");
    prefEditor.commit();
    assignInfoToHistoryTextView();
}

Каждая функция создает общий параметр с именем lastpacketsPHP и помещает в него другой URL-адрес.Когда метод assignInfoToHistoryTextView вызывается, он вызывает другую функцию, расположенную в другом файле класса.Класс показан ниже:

package shc_BalloonSat.namespace;

import java.text.DecimalFormat;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SubMenu;
import android.widget.TextView;
import android.widget.Toast;

public class Shc_BalloonSat_Activity extends Activity
{
int historyCountFromUser;
httpAPI api = new httpAPI(this);
kmlAPI kml = new kmlAPI(this);
DecimalFormat df = new DecimalFormat("##.#####");
DecimalFormat decimalf = new DecimalFormat("##.######");
SharedPreferences pref;
Editor prefEditor;
String lastpacketsPHP;

// User to determine how many packet the user would like to see.
int userDefinedCount = 4;

/** Called when the activity is first created. 
 * @param view */

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    String returned = null;
    prefEditor.putString(lastpacketsPHP, "http://www.wktechnologies.com/shc_android_app/get_last_5_BS_packets.php");

    try
    {
        returned = api.getData();
    }

    catch (Exception e)
    {
        e.printStackTrace();
    }

    TextView infoTV = (TextView)this.findViewById(R.id.info);
    infoTV.setText(returned);
    assignInfoToInfoTextView();
    assignInfoToHistoryTextView();
}

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.mainmenu, menu);

    SubMenu submenu = menu.addSubMenu(0, Menu.FIRST, Menu.NONE, "Preferences");
    submenu.add(0, 5, Menu.NONE, "Get Last 5 Packets");
    submenu.add(0, 10, Menu.NONE, "Get Last 10 Packets");
    submenu.add(0, 20, Menu.NONE, "Get Last 20 Packets");
    inflater.inflate(R.menu.mainmenu, submenu);

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    // Handle item selection
    switch (item.getItemId())
    {
        case R.id.viewKML:
            viewKML();
            return true;
        case 5:
            viewLast5Packets();
            return true;
        case 10:
            viewLast10Packets();
            return true;
        case 20:
            viewLast5Packets();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

public void assignInfoToInfoTextView()
{
    TextView infoTV = (TextView)this.findViewById(shc_BalloonSat.namespace.R.id.info); 

    try
    {
        JSONArray jArray = new JSONArray(api.result);
        for (int count = 0; count < 2; count++)
        {
            JSONObject json_data = jArray.getJSONObject(count);

            double altitudeData = json_data.getDouble("altitude");
            String infoText = "Last Known Altitude: " + df.format(altitudeData) + "\n";

            Double speedData = json_data.optDouble("speed");

            if (speedData.isNaN())
            {
                speedData = 0.00;
            }

            infoText += "Last Known Speed: " + df.format(speedData) + "\n";

            double recentLatitudeData = json_data.getDouble("latitude");
            infoText += "Last Known Latitude: " + df.format(recentLatitudeData) + "\n";

            double recentLongitudeData = json_data.getDouble("longitude");
            infoText += "Last Known Longtitude: " + df.format(recentLongitudeData) + "\n";

            infoTV.setText(infoText);
        }
    }

    catch (JSONException e)
    {
        // TODO Auto-generated catch block
        Log.e("<tag>", e.getMessage());
        Toast.makeText(this,"Error in (Last Known) method!",Toast.LENGTH_SHORT).show();
    }
}

public void assignInfoToHistoryTextView()
{
    try
    {
        JSONArray jArray = new JSONArray(api.result);

        for (int count = 1; count <= userDefinedCount; count++)
        {
            TextView historyTV = (TextView)this.findViewById(shc_BalloonSat.namespace.R.id.history);
            JSONObject json_data = jArray.getJSONObject(count);

            double altitudeData = json_data.getDouble("altitude");
            String historyText = "Altitude: " + decimalf.format(altitudeData) + "\n";

            Double speedData = json_data.optDouble("speed");

            if (speedData.isNaN())
            {
                speedData = 0.00;
            }

            historyText += "Speed: " + df.format(speedData) + "\n";

            double latitudeData = json_data.getDouble("latitude");
            historyText += "Latitude: " + df.format(latitudeData) + "\n";

            double longitudeData = json_data.getDouble("longitude");
            historyText += "Longtitude: " + df.format(longitudeData) + "\n\n";

            historyTV.append(historyText);
        }
    }

    catch (JSONException e)
    {
        // TODO Auto-generated catch block
        Log.e("log_tag", "Error parsing data: " + e.toString());
    }

}

void viewLast5Packets()
{
    userDefinedCount = 4;
    prefEditor.putString(lastpacketsPHP, "http://www.wktechnologies.com/shc_android_app/get_last_5_BS_packets.php");
    prefEditor.commit();
    assignInfoToHistoryTextView();
}

void viewLast10Packets()
{
    userDefinedCount = 9;
    prefEditor.putString(lastpacketsPHP, "http://www.wktechnologies.com/shc_android_app/get_last_10_BS_packets.php");
    prefEditor.commit();
    assignInfoToHistoryTextView();
}

void viewLast20Packets()
{
    userDefinedCount = 19;
    prefEditor.putString(lastpacketsPHP, "http://www.wktechnologies.com/shc_android_app/get_last_20_BS_packets.php");
    prefEditor.commit();
    assignInfoToHistoryTextView();
}

public void viewKML()
{
    kml.openKML();
}
}

В httpPost я пытаюсь установить его так, чтобы он вызывал тот файл PHP, который был выбран в зависимости от того, какой вариант был выбран пользователем.Я делаю это, вставляя получить значение предпочтения и помещая его в httpPost.Когда я запускаю приложение в эмуляторе, оно сразу падает, и этого не произошло, пока я не поместил код предпочтения в httpPost, чтобы я знал, что мой синтаксис неправильный, я просто не знаю, что я делаю неправильно.Любая помощь будет принята с благодарностью.

Я получаю эти ошибки во время выполнения с кодом выше:

02-02 13:42:14.973: E/AndroidRuntime(230): Uncaught handler: thread main exiting due to uncaught exception
02-02 13:42:15.213: D/dalvikvm(230): GC freed 3178 objects / 319424 bytes in 131ms
02-02 13:42:15.283: E/AndroidRuntime(230): java.lang.StackOverflowError
02-02 13:42:15.283: E/AndroidRuntime(230):  at java.lang.Thread.currentThread(Thread.java:588)
02-02 13:42:15.283: E/AndroidRuntime(230):  at java.lang.ThreadLocal.get(ThreadLocal.java:59)
02-02 13:42:15.283: E/AndroidRuntime(230):  at android.os.Looper.myLooper(Looper.java:137)
02-02 13:42:15.283: E/AndroidRuntime(230):  at android.os.Handler.<init>(Handler.java:119)
02-02 13:42:15.283: E/AndroidRuntime(230):  at android.app.Activity.<init>(Activity.java:673)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.Shc_BalloonSat_Activity.<init>(Shc_BalloonSat_Activity.java:21)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.httpAPI.<init>(httpAPI.java:20)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.Shc_BalloonSat_Activity.<init>(Shc_BalloonSat_Activity.java:24)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.httpAPI.<init>(httpAPI.java:20)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.Shc_BalloonSat_Activity.<init>(Shc_BalloonSat_Activity.java:24)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.httpAPI.<init>(httpAPI.java:20)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.Shc_BalloonSat_Activity.<init>(Shc_BalloonSat_Activity.java:24)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.httpAPI.<init>(httpAPI.java:20)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.Shc_BalloonSat_Activity.<init>(Shc_BalloonSat_Activity.java:24)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.httpAPI.<init>(httpAPI.java:20)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.Shc_BalloonSat_Activity.<init>(Shc_BalloonSat_Activity.java:24)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.httpAPI.<init>(httpAPI.java:20)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.Shc_BalloonSat_Activity.<init>(Shc_BalloonSat_Activity.java:24)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.httpAPI.<init>(httpAPI.java:20)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.Shc_BalloonSat_Activity.<init>(Shc_BalloonSat_Activity.java:24)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.httpAPI.<init>(httpAPI.java:20)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.Shc_BalloonSat_Activity.<init>(Shc_BalloonSat_Activity.java:24)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.httpAPI.<init>(httpAPI.java:20)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.Shc_BalloonSat_Activity.<init>(Shc_BalloonSat_Activity.java:24)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.httpAPI.<init>(httpAPI.java:20)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.Shc_BalloonSat_Activity.<init>(Shc_BalloonSat_Activity.java:24)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.httpAPI.<init>(httpAPI.java:20)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.Shc_BalloonSat_Activity.<init>(Shc_BalloonSat_Activity.java:24)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.httpAPI.<init>(httpAPI.java:20)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.Shc_BalloonSat_Activity.<init>(Shc_BalloonSat_Activity.java:24)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.httpAPI.<init>(httpAPI.java:20)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.Shc_BalloonSat_Activity.<init>(Shc_BalloonSat_Activity.java:24)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.httpAPI.<init>(httpAPI.java:20)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.Shc_BalloonSat_Activity.<init>(Shc_BalloonSat_Activity.java:24)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.httpAPI.<init>(httpAPI.java:20)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.Shc_BalloonSat_Activity.<init>(Shc_BalloonSat_Activity.java:24)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.httpAPI.<init>(httpAPI.java:20)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.Shc_BalloonSat_Activity.<init>(Shc_BalloonSat_Activity.java:24)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.httpAPI.<init>(httpAPI.java:20)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.Shc_BalloonSat_Activity.<init>(Shc_BalloonSat_Activity.java:24)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.httpAPI.<init>(httpAPI.java:20)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.Shc_BalloonSat_Activity.<init>(Shc_BalloonSat_Activity.java:24)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.httpAPI.<init>(httpAPI.java:20)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.Shc_BalloonSat_Activity.<init>(Shc_BalloonSat_Activity.java:24)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.httpAPI.<init>(httpAPI.java:20)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.Shc_BalloonSat_Activity.<init>(Shc_BalloonSat_Activity.java:24)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.httpAPI.<init>(httpAPI.java:20)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.Shc_BalloonSat_Activity.<init>(Shc_BalloonSat_Activity.java:24)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.httpAPI.<init>(httpAPI.java:20)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.Shc_BalloonSat_Activity.<init>(Shc_BalloonSat_Activity.java:24)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.httpAPI.<init>(httpAPI.java:20)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.Shc_BalloonSat_Activity.<init>(Shc_BalloonSat_Activity.java:24)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.httpAPI.<init>(httpAPI.java:20)
02-02 13:42:15.283: E/AndroidRuntime(230):  at shc_BalloonSat.namespace.Shc_BalloonSat_Activity.<init>(Shc_BalloonSat_Activity.

02-02 13:42:15.373: I/dalvikvm(230): threadid=7: reacting to signal 3
02-02 13:42:15.373: E/dalvikvm(230): Unable to open stack trace file '/data/anr/traces.txt': Permission denied

1 Ответ

2 голосов
/ 02 февраля 2012
public class httpAPI
{
    Shc_BalloonSat_Activity shc;

    ...

        httppost = new HttpPost(shc.pref.getString(shc.lastpacketsPHP,
                                shc.lastpacketsPHP.toString()));

Изначально проблема заключалась в том, что shc использовался без инициализации. В ответ на вопрос, поскольку объекту HttpPost требуется экземпляр SharedPreferences (который доступен через контекст), я бы предложил добавить конструктор в класс httpAPI. Например:

public class httpAPI {

    Shc_BalloonSat_Activity shc;
    HttpPost httppost;

    ...

    public httpAPI(Shc_BalloonSat_Activity aContext) {
        shc = aContext;
    }

    ...

    public String getData() throws Exception {
        ...
        httppost = new HttpPost(shc.pref.getString(shc.lastpacketsPHP, shc.lastpacketsPHP.toString());
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...