【发布时间】:2016-02-12 09:54:11
【问题描述】:
我必须点击服务,如果响应正确,我必须验证用户并将用户输入的变量保存在共享首选项中。我的网址是:http://a.nextput.com/apps/init/4/a/9fe2d2cbaa8332a4633be17b79208181-2y-10-ELVM4HwkaYaCVu6203Zjfus-G/o?aff_id,它给出的响应是 {"success":true}。为此,我创建了一个类并声明了一个静态方法。在静态方法中,我必须进行解析。 我的班级:
public class InitializeSDK {
/*String json = "";
URL url;
HttpURLConnection connection = null;*/
public static void init(final Context ctx, int offerwall_id, String offerwall_public_key) {
new AsyncTask<Void, Void, Void>() {
protected void onPreExecute() {
super.onPreExecute();
}
protected Void doInBackground(Void... arg0) {
//TODO: add code to read http request and store the json data in json variable
String json = "";
//URL url;
HttpURLConnection connection = null;
InputStream is = null;
final String MyPREFERENCES = "MyPrefs" ;
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://a.nextput.com/apps/init/4/a/9fe2d2cbaa8332a4633be17b79208181-2y-10-ELVM4HwkaYaCVu6203Zjfus-G/o?aff_id");//YOUR URL
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
JSONObject jObj = new JSONObject(json);
boolean isSuccess = jObj.getBoolean("success");
System.out.println("success : " + isSuccess);
// SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
/*SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Context ctx);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("isSuccess",isSuccess);
editor.commit();*/
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
/* JSONObject jsonObject = new JSONObject(json);
boolean state = jsonObject.getBoolean("success");*/
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}.execute();
}
我的 MainActivity 是:
public class MainActivity extends AppCompatActivity {
final Context context = this;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
}
如何保存sharedpreference中的变量并将类与MainActivity连接起来?请帮忙
【问题讨论】:
-
“用 MainActivity 连接类”是什么意思?
-
我猜他不知道如何在他的 Activity 中“使用”他的 InitializeSDK 类
-
你能帮忙吗?
-
除了成功消息先更新您的 api 之外,您没有任何值可解析
标签: java android android-intent sharedpreferences