2016-08-04 1 views
0

저는 잠시 동안 어려움을 겪어 왔지만 실제로 도움이되는 것을 찾지 않고 몇 시간 동안 여기를 수색했습니다. 맞춤 클래스가 있습니다 Streak. 사용자가 내 기본 활동에 새로운 Streak을 만들면 해당 줄무늬가 총 줄무늬 목록에 추가되고 난 후 AllStreaks 활동에서 액세스하게됩니다. Gson을 사용해 보았지만 오류가 발생했습니다. 아래에 나와있는 것은 당분간 작동하지만 내 전역 변수는 새로운 것으로 선언되어야하므로 이 정보는 신속하게 편집 할 수 있어야하며 잠재적으로 단 한 가지 세부 정보 만 변경하도록 끊임없이 연결하고 싶지는 않으므로 MySQL 데이터베이스를 사용하고 싶지는 않습니다.안드로이드 - 사용자 정의 객체의 ArrayList를 다른 액티비티에 전달하기

죄송합니다. 내 코드가 엉망이거나 말도 안되는 경우, 필자는 어쨌든 프로그래밍에 정말 엿 같은 것을 깨닫게 될 것입니다.

MainActivity.java

:

public class MainActivity extends AppCompatActivity { 

private SharedPreferences prefs; 
private SharedPreferences.Editor editor; 
private String userID; 

private int streakCounter; 
private int mainStreakCounter; 

private RelativeLayout quickAdd; 
private EditText quickSubmitStreak; 
private Button quickSubmitButton; 
private Button mainStreak1; 
private Button mainStreak2; 
private Button mainStreak3; 
private Button mainStreak4; 
private Button allStreaks; 
private Button addStreak; 

private Dialog pickDialog; 

private Button healthButton; 
private Button mentalButton; 
private Button personalButton; 
private Button professionalButton; 
private Button socialButton; 

private Button submitStreakButton; 
private TextView todaysDate; 
private EditText chooseDate; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 

    /* 
     Creates shared preferences and editor 
    */ 
    prefs = getSharedPreferences("carter.streakly", MODE_PRIVATE); 
    editor = prefs.edit(); 

    // Checks if it's the first time the user opens the app. If so, generates a unique user ID and stores it in shared prefs 
    if (prefs.getBoolean("firstTime", true)){ 
     userID = UUID.randomUUID().toString(); 
     editor.putString("user", userID); 
     editor.putBoolean("firstTime", false); 
     editor.commit(); 
    } 

    streakCounter = 0; // CHANGE TO streakCounter = prefs.getInt("streakCounter", 0) later 
    mainStreakCounter = 0; // CHANGE TO mainStreakCount = prefs.getInt("mainStreakCounter", 0) later 
    quickSubmitStreak = (EditText) findViewById(R.id.enter_goal); 
    quickSubmitButton = (Button) findViewById(R.id.submit_button); 
    mainStreak1 = (Button) findViewById(R.id.main_goal_1); 
    mainStreak2 = (Button) findViewById(R.id.main_goal_2); 
    mainStreak3 = (Button) findViewById(R.id.main_goal_3); 
    mainStreak4 = (Button) findViewById(R.id.main_goal_4); 
    allStreaks = (Button) findViewById(R.id.main_goal_5); 
    addStreak = (Button) findViewById(R.id.add_streak_button); 


    /* 
    if (streakCounter > 4){ 
     quickAdd.setVisibility(View.INVISIBLE); 
    } 


    mainStreak1.setText(prefs.getString("mainKeyOne", "")); 
    mainStreak2.setText(prefs.getString("mainKeyTwo", "")); 
    mainStreak3.setText(prefs.getString("mainKeyThree", "")); 
    mainStreak4.setText(prefs.getString("mainKeyFour", "")); 


    /* 
     Sets the text to the lowest unused main streak to the inputted streak name 
     Stores the streak name in shared prefs so it will be there for next time app opens 
     Increases the total streak count 
    */ 
    quickSubmitButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      if (mainStreakCounter < 4){ 
       switch(mainStreakCounter){ 
        case 0: 
         mainStreak1.setText(quickSubmitStreak.getText().toString()); 
         editor.putString("mainKeyOne", quickSubmitStreak.getText().toString()).commit(); 
         break; 
        case 1: 
         mainStreak2.setText(quickSubmitStreak.getText().toString()); 
         editor.putString("mainKeyTwo", quickSubmitStreak.getText().toString()).commit(); 
         break; 
        case 2: 
         mainStreak3.setText(quickSubmitStreak.getText().toString()); 
         editor.putString("mainKeyThree", quickSubmitStreak.getText().toString()).commit(); 
         break; 
        case 3: 
         mainStreak4.setText(quickSubmitStreak.getText().toString()); 
         editor.putString("mainKeyFour", quickSubmitStreak.getText().toString()).commit(); 
         break; 
        default:break; 
       } 
      } 
      mainStreakCounter++; 
      AllStreaks.streakList.add(new Streak(quickSubmitStreak.getText().toString())); 

      // ADD THESE TO SHARED PREFERENCES AT SOME POINT 
     } 

    }); 

    /* 
     Brings user to the All Streaks activity, and passes the LinkedList<Streak> streakList 
    */ 
    allStreaks.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      Intent intent = new Intent(MainActivity.this, AllStreaks.class); 
      startActivity(intent); 
     } 
    }); 

    /* 
     Shows an Alert Dialog that allows users to enter in the type of streak they want 
    */ 
    addStreak.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      createCustomDialog(); 
     } 
    }); 
} 

private void createCustomDialog(){ 
    pickDialog = new Dialog(MainActivity.this); 
    pickDialog.setContentView(R.layout.dialog_add_streak); 

    final EditText chooseName = (EditText) pickDialog.findViewById(R.id.dialog_acitivty_name); 
    healthButton = (Button) pickDialog.findViewById(R.id.dialog_health); 
    mentalButton = (Button) pickDialog.findViewById(R.id.dialog_mental); 
    personalButton = (Button) pickDialog.findViewById(R.id.dialog_personal); 
    professionalButton = (Button) pickDialog.findViewById(R.id.dialog_professional); 
    socialButton = (Button) pickDialog.findViewById(R.id.dialog_social); 
    submitStreakButton = (Button) pickDialog.findViewById(R.id.dialog_submit_button); 
    todaysDate = (TextView) pickDialog.findViewById(R.id.dialog_today); 
    chooseDate = (EditText) pickDialog.findViewById(R.id.dialog_input_date); 

    pickDialog.show(); 

    healthButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      editor.putInt("AddCategory", 0).commit(); 
      editor.putString("Category", "Health"); 
      editor.commit(); 
      recolorCategory(); 
     } 
    }); 

    mentalButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      editor.putInt("AddCategory", 1).commit(); 
      editor.putString("Category", "Mental"); 
      editor.commit(); 
      recolorCategory(); 
     } 
    }); 

    personalButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      editor.putInt("AddCategory", 2).commit(); 
      editor.putString("Category", "Personal"); 
      editor.commit(); 
      recolorCategory(); 
     } 
    }); 

    professionalButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      editor.putInt("AddCategory", 3).commit(); 
      editor.putString("Category", "Professional"); 
      editor.commit(); 
      recolorCategory(); 
     } 
    }); 

    socialButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      editor.putInt("AddCategory", 4).commit(); 
      editor.putString("Category", "Social"); 
      editor.commit(); 
      recolorCategory(); 
     } 
    }); 

    todaysDate.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      todaysDate.setTextColor(Color.rgb(51,51,255)); 
      chooseDate.setTextColor(Color.rgb(0,0,0)); 
      editor.putInt("todayOrChosen", 1).commit(); 
     } 
    }); 

    chooseDate.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      chooseDate.setTextColor(Color.rgb(51,51,255)); 
      todaysDate.setTextColor(Color.rgb(0,0,0)); 
      editor.putInt("todayOrChosen", 2).commit(); 
     } 
    }); 


    submitStreakButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      /* 
       If the user selected today's date, enter the days kept as 0. If the user selected how long they've kept the streak for, enter the days kept as chooseDate 
      */ 
      if(prefs.getInt("todayOrChosen", 1) == 1){ 
       //streakList.add(new Streak(chooseName.getText().toString(), prefs.getString("Category", ""), 
         //new SimpleDateFormat("dd-MM-yyyy").format(new Date()), 0)); 
       AllStreaks.streakList.add(new Streak(chooseName.getText().toString(), prefs.getString("Category", ""), 
         new SimpleDateFormat("dd-MM-yyyy").format(new Date()), 0)); 
      } 
      else { 
       //streakList.add(new Streak(chooseName.getText().toString(), prefs.getString("Category", ""), 
         //new SimpleDateFormat("dd-MM-yyyy").format(new Date()), Integer.parseInt(chooseDate.getText().toString()))); 
       AllStreaks.streakList.add(new Streak(chooseName.getText().toString(), prefs.getString("Category", ""), 
         new SimpleDateFormat("dd-MM-yyyy").format(new Date()), Integer.parseInt(chooseDate.getText().toString()))); 
      } 

      /* 
       Update streakList in Shared Preferences 
      */ 

      /* 
       Display an Alert Dialog indicating that a streak has been added 
      */ 
      AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); 
      builder.setMessage("Streak Added") 
        .setPositiveButton("OK", null) 
        .create() 
        .show(); 

      pickDialog.dismiss(); 
     } 
    }); 
} 

/* 
    Highlights which category is currently chosen 
*/ 
private void recolorCategory(){ 
    Button[] categoryList = {healthButton, mentalButton, personalButton, professionalButton, socialButton}; 
    int recolorIndex = prefs.getInt("AddCategory", 0); 
    categoryList[recolorIndex].setTextColor(Color.rgb(51,51,255)); 
    for (int i = 0; i < 5; i++){ 
     if (i != recolorIndex) categoryList[i].setTextColor(Color.rgb(153, 255, 102)); 
    } 
} 

@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); 
} 
} 

AllStreaks.java는 :

public class AllStreaks extends AppCompatActivity { 
public static ArrayList<Streak> streakList = new ArrayList<>(); 

private SharedPreferences prefs; 
private SharedPreferences.Editor editor; 

private ArrayList<Streak> allStreakList; 

private TableLayout mTableLayout; 
private TableRow mTableRow; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_all_streaks); 
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 



    /* 
    if (streakList == null){ 
     Button streakButton = new Button(this); 
     streakButton.setText("Try again"); 
    } 
    else{ 
     for (int j = 0; j < streakList.size(); j++){ 
      allStreakList.add(streakList.get(j)); 
     } 
    }*/ 

    prefs = getSharedPreferences("carter.streakly", MODE_PRIVATE); 
    editor = prefs.edit(); 

    mTableLayout = (TableLayout) findViewById(R.id.all_streak_table); 

    int i = 0; 
    while (i < streakList.size()){ 
     if (i % 2 == 0){ 
      mTableRow = new TableRow(this); 
      mTableLayout.addView(mTableRow); 
     } 
     Button streakButton = new Button(this); 
     streakButton.setText(String.valueOf(streakList.get(i).getDaysKept())); 
     streakButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       Intent intent = new Intent(AllStreaks.this, EnlargedActivity.class); 
       startActivity(intent); 
      } 
     }); 
     mTableRow.addView(streakButton); 
     i++; 
    } 
} 
} 
+0

주요 활동 행진되는 ArrayList를 만들고 parcelable을 사용 의도를 통과 :

ArrayList carList = new ArrayList(); carList.add(new Car('1','Honda','Black'); carList.add(new Car('2','Toyota','Blue'); carList.add(new Car('3','Suzuki','Green'); Intent i = new Intent(getApplicationContext(), CarDetailActivity.class); i.putParcelableArrayListExtra("cars", carList); this.startActivity(i); 

아래처럼 얻을 수 있습니다. getIntent(). getParcelableArrayExtra()를 사용하여 Streak 클래스를 parcelable 및 retrive로 만드는 것을 의미합니다. AllStreak 활동. AllStreak 클래스에 정적 arrylist를 만드는 대신. – mcd

+0

당신은 내가 그것을 보여준 것을 볼 수 있습니다. –

답변

0

당신은 Parcelable 또는 Serializable 인터페이스를 사용해야합니다.

의도와 패스 그것을

Intent mIntent = new Intent(context, ResultActivity.class); 
mIntent.putParcelableArrayListExtra("list", mArraylist); 
startActivity(mIntent); 

, 당신의 Streak 클래스에서이 작업을 수행하고 시도 참조

Bundle bundle = getIntent().getExtras(); 
mArraylist1 = bundle.getParcelableArrayList("list"); 

확인 this 스레드 ResultActivity에

+0

이 방법이 효과적이지만 AllStreaks 클래스에이 값을 저장하는 방법은 무엇입니까? AllStreak에 전달 된 ArrayList에 새로운 줄무늬를 추가합니다. 앱을 죽이고 다시 열면 AllStreaks.java는 다시 비어 있습니다. 새로운 것을 추가하지 않았기 때문입니다. –

+0

그럴 경우 해당 데이터를 오프라인으로 유지해야합니다. 그 대신 SQLite를 사용하여 –

0

그것을 가져

Streak implements Parcelable 

모달 클래스가 직렬화되지 않았으므로 번들을 통해 전달할 수 없습니다. Parcelable 인터페이스를 구현하면됩니다.

  1. Parcelable은 직접 직렬화를 구현하는 Android 전용 인터페이스입니다. Serializable보다 훨씬 효율적으로 작성되었으며 기본 Java 직렬화 구성에서 몇 가지 문제점을 해결합니다.
  2. Serializable은 표준 Java 인터페이스입니다. 인터페이스를 구현하여 클래스 Serializable을 표시하기 만하면 특정 상황에서 Java가 으로 자동 직렬화됩니다. Courtsy
+0

대신 serialize 가능한 parcelable을 사용하는 것이 더 빠릅니다. – mcd

+0

@mcd 네, 맞습니다. Parcelable은 안드로이드 특정 인터페이스입니다, 나는 내 대답을 업데이 트됩니다. – LvN

0

당신은 parcelable 또는 직렬화해야 directly.you 개체를 전달할 수 없습니다. 하지만 parecelable 안드로이드의 일부는 serialzation 자바의 일부로 그래서 나는 parcelable 사용하는 것이 좋습니다.

parcelabel을 코딩하고 싶지 않으면이 링크에서 모델 클래스를 parcelable로 만들 수 있습니다.

parcelable creator

당신은 다음과 같이 얻을 수 있습니다.

class Car implements Parcelable { 
public int regId; 
public String brand; 
public String color; 

public Car(Parcel source) { 
    regId = source.getInt(); 
    brand = source.getString(); 
    color = source.getString(); 
} 

public Car(int regId, String brand, String color) { 
    this.regId = regId; 
    this.brand = brand; 
    this.color = color; 
} 

public int describeContents() { 
return this.hashCode(); 
} 

public void writeToParcel(Parcel dest, int flags) { 
dest.writeInt(regId); 
dest.writeString(brand); 
dest.writeString(color); 
} 

public static final Parcelable.Creator CREATOR 
     = new Parcelable.Creator() { 
    public Car createFromParcel(Parcel in) { 
     return new Car(in); 
    } 

    public Car[] newArray(int size) { 
     return new Car[size]; 
    } 
};} 

다음과 같이 전달할 수 있습니다.

Intent i = this.getIntent(); 
ArrayList<Car> carList = (ArrayList<Car>)i.getParcelableArrayListExtra("cars");` 
관련 문제