Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/393.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将字符串值从活动发送到异步任务?_Java_Android_Android Asynctask - Fatal编程技术网

Java 如何将字符串值从活动发送到异步任务?

Java 如何将字符串值从活动发送到异步任务?,java,android,android-asynctask,Java,Android,Android Asynctask,我有一个IzborKategorija.java活动,其中根据用户的复选框选择创建字符串,我需要将该字符串作为url的最后一部分发送到asyncTask,我使用它来生成GET方法。因此,我创建了如下字符串:3,6,7,9,我需要将该字符串附加到“+regid+”和channels_id=“+STRINGFROMACTIVITY”。 我的AsyncTask已经在等待从GCM注册,如何在那里再添加一个参数 我的活动IzborKategorija.java: import java.util.Arra

我有一个IzborKategorija.java活动,其中根据用户的复选框选择创建字符串,我需要将该字符串作为url的最后一部分发送到asyncTask,我使用它来生成GET方法。因此,我创建了如下字符串:3,6,7,9,我需要将该字符串附加到“+regid+”和channels_id=“+STRINGFROMACTIVITY”。 我的AsyncTask已经在等待从GCM注册,如何在那里再添加一个参数

我的活动IzborKategorija.java:

import java.util.ArrayList;
import java.util.Arrays;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class IzborKategorija extends Activity{
    ListView myList;
    Button getChoice, clearAll;
    SharedPreferences sharedpreferences;
    public static final String MyPREFERENCES = "MyUserChoice" ;
    ArrayList<String> selectedItems = new ArrayList<String>();
    private static final String TAG = "KATARINA";
    String savedItems;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        myList = (ListView)findViewById(R.id.list);
        getChoice = (Button)findViewById(R.id.getchoice);
        clearAll = (Button)findViewById(R.id.clearall);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, getResources().getStringArray(R.array.Mobile_OS));
        myList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        myList.setAdapter(adapter);

        sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
        if(sharedpreferences.contains(MyPREFERENCES)){
            LoadSelections();
        }

        getChoice.setOnClickListener(new Button.OnClickListener(){


            @Override
            public void onClick(View v) {

                String selected = "";
                int cntChoice = myList.getCount();

                SparseBooleanArray sparseBooleanArray = myList.getCheckedItemPositions();
                for(int i = 0; i < cntChoice; i++){
                    if(sparseBooleanArray.get(i)) {
                        selected += myList.getItemAtPosition(i).toString() + "\n";
                        System.out.println("Checking list while adding:" + myList.getItemAtPosition(i).toString());
                        SaveSelections();
                    }

                }


                Toast.makeText(IzborKategorija.this, selected, Toast.LENGTH_LONG).show();

            }});

        clearAll.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
// TODO Auto-generated method stub
                ClearSelections();
            }
        });


    }

    private void SaveSelections() {
// save the selections in the shared preference in private mode for the user

        SharedPreferences.Editor prefEditor = sharedpreferences.edit();
        String savedItems = getSavedItems();
        prefEditor.putString(MyPREFERENCES.toString(), savedItems);
        prefEditor.commit();
    }

    private String getSavedItems() {
        String savedItems = "";
        int count = this.myList.getAdapter().getCount();
        for (int i = 0; i < count; i++) {
            if (this.myList.isItemChecked(i)) {
                if (savedItems.length() > 0) {
                    savedItems += "," + this.myList.getItemAtPosition(i);
                } else {
                    savedItems += this.myList.getItemAtPosition(i);
                }
            }
        }

        savedItems = savedItems.replaceAll("[^0-9,]", "");
        Log.i(TAG, "SPISAK ODABRANIH: " + savedItems);
        return savedItems;


    }


    private void LoadSelections() {
// if the selections were previously saved load them

        if (sharedpreferences.contains(MyPREFERENCES.toString())) {

            String savedItems = sharedpreferences.getString(MyPREFERENCES.toString(), "");
            selectedItems.addAll(Arrays.asList(savedItems.split(",")));

            int count = this.myList.getAdapter().getCount();

            for (int i = 0; i < count; i++) {
                String currentItem = (String) myList.getAdapter()
                        .getItem(i);
                if (selectedItems.contains(currentItem)) {
                    myList.setItemChecked(i, true);
                    Toast.makeText(getApplicationContext(),
                            "Curren Item: " + currentItem,
                            Toast.LENGTH_LONG).show();
                } else {
                    myList.setItemChecked(i, false);
                }

            }
        }
    }

   private void ClearSelections() {
// user has clicked clear button so uncheck all the items
        int count = this.myList.getAdapter().getCount();
        for (int i = 0; i < count; i++) {
            this.myList.setItemChecked(i, false);
        }
// also clear the saved selections
        SaveSelections();
    }

}
import java.util.ArrayList;
导入java.util.array;
导入android.app.Activity;
导入android.content.Context;
导入android.content.Intent;
导入android.content.SharedReferences;
导入android.os.Bundle;
导入android.util.Log;
导入android.util.SparseBooleanArray;
导入android.view.view;
导入android.widget.ArrayAdapter;
导入android.widget.Button;
导入android.widget.ListView;
导入android.widget.Toast;
公共类IzborKategorija扩展活动{
列表视图myList;
按钮getChoice,clearAll;
SharedReferences SharedReferences;
公共静态最终字符串MyPREFERENCES=“MyUserChoice”;
ArrayList selectedItems=新建ArrayList();
私有静态最终字符串TAG=“KATARINA”;
字符串保存数据项;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
//TODO自动生成的方法存根
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myList=(ListView)findViewById(R.id.list);
getChoice=(按钮)findViewById(R.id.getChoice);
clearAll=(按钮)findViewById(R.id.clearAll);
ArrayAdapter=新的ArrayAdapter(这个,android.R.layout.simple_list_item_多选,getResources().getStringArray(R.array.Mobile_OS));
myList.setChoiceMode(ListView.CHOICE\u MODE\u MULTIPLE);
myList.setAdapter(适配器);
SharedReferences=GetSharedReferences(MyPREFERENCES,Context.MODE\u PRIVATE);
if(SharedReferences.contains(MyPREFERENCES)){
LoadSelections();
}
getChoice.setOnClickListener(新建按钮.OnClickListener(){
@凌驾
公共void onClick(视图v){
所选字符串=”;
int cntChoice=myList.getCount();
SparseBooleanArray SparseBooleanArray=myList.getCheckedItemPositions();
for(int i=0;i0){
savedItems+=“,”+this.myList.getItemAtPosition(i);
}否则{
savedItems+=this.myList.getItemAtPosition(i);
}
}
}
savedItems=savedItems.replaceAll(“[^0-9,]”,“”);
Log.i(标签“SPISAK ODABRANIH:+savedItems”);
返回savedItems;
}
私有void LoadSelections(){
//如果以前保存了选择,请加载它们
if(SharedReferences.contains(MyPREFERENCES.toString())){
String savedItems=SharedReferences.getString(MyPREFERENCES.toString(),“”);
选择editems.addAll(Arrays.asList(savedItems.split(“,”));
int count=this.myList.getAdapter().getCount();
for(int i=0;i
My AsyncTask RegisterApp.java:

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.client.ClientProtocolException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;


public class RegisterApp extends AsyncTask<Void, Void, String> {

 private static final String TAG = "GCMRelated";
 Context ctx;
 GoogleCloudMessaging gcm;
 String SENDER_ID = "980800840437";
 String regid = null;
 private int appVersion;
 public RegisterApp(Context ctx, GoogleCloudMessaging gcm, int appVersion){
  this.ctx = ctx;
  this.gcm = gcm;
  this.appVersion = appVersion;
 }


 @Override
 protected void onPreExecute() {
  super.onPreExecute();
 }


 @Override
 protected String doInBackground(Void... arg0) {


     String msg = "";
        try {
            if (gcm == null) {
                gcm = GoogleCloudMessaging.getInstance(ctx);
            }
            regid = gcm.register(SENDER_ID);
            msg = "Device registered, registration ID=" + regid;

            // You should send the registration ID to your server over HTTP,
            // so it can use GCM/HTTP or CCS to send messages to your app.
            // The request to your server should be authenticated if your app
            // is using accounts.
            sendRegistrationIdToBackend();

            // For this demo: we don't need to send it because the device
            // will send upstream messages to a server that echo back the
            // message using the 'from' address in the message.

            // Persist the regID - no need to register again.
            storeRegistrationId(ctx, regid);
        } catch (IOException ex) {
            msg = "Error :" + ex.getMessage();
            // If there is an error, don't just keep trying to register.
            // Require the user to click a button again, or perform
            // exponential back-off.
        }
        return msg;

 }


 private void storeRegistrationId(Context ctx, String regid) {
  final SharedPreferences prefs = ctx.getSharedPreferences(MainActivity.class.getSimpleName(),
             Context.MODE_PRIVATE);
     Log.i(TAG, "Saving regId on app version " + appVersion);
     SharedPreferences.Editor editor = prefs.edit();
     editor.putString("registration_id", regid);
     editor.putInt("appVersion", appVersion);
     editor.commit();

 }




    private void sendRegistrationIdToBackend() throws IOException {

        URL obj = new URL("http://www.example.com/push/?device_token="+regid+"&channels_id="+STRINGFROMACTIVITY);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        int responseCode = con.getResponseCode();
        System.out.println("GET Response Code :: " + responseCode);
        if (responseCode == HttpURLConnection.HTTP_OK) { // success
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // print result
            System.out.println(response.toString());

            Log.i(TAG, "OVO SAM POSLAO " + savedItems);

        } else {
            System.out.println("GET request not worked");
        }

    }



 @Override
 protected void onPostExecute(String result) {
  super.onPostExecute(result);
  Toast.makeText(ctx, "Registration Completed. Now you can see the notifications", Toast.LENGTH_SHORT).show();
  Log.v(TAG, result);
 }
}
import java.io.IOException;
导入java.net.URI;
导入java.net.URISyntaxException;
导入org.apache.http.client.ClientProtocolException;
导入java.io.BufferedReader;
导入java.io.InputStreamReader;
导入java.io.OutputStream;
导入java.net.HttpURLConnection;
导入java.net.URL;
导入com.google.android.gms.gcm.GoogleCloudMessaging;
导入android.content.Context;
导入android.content.Intent;
导入android.content.SharedReferences;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.preference.PreferenceManager;
导入android.util.Log;
导入android.widget.Toast;
公共类RegisterApp扩展异步任务{
专用静态fi
new RegisterApp(STRINGFROMACTIVITY).execute();
String STRINGFROMACTIVITY;  //create string variable in RegisterApp
......
......

public RegisterApp(String STRINGFROMACTIVITY){
  this.STRINGFROMACTIVITY= STRINGFROMACTIVITY;
 }